All topics
50

Removing the nth node from the end

Tier 1Locked

Where it runs

1. The problem

Delete the 2nd node from the end of a list. On an array that is one line: arr.splice(arr.length - 2, 1). The array knows its length. A linked list is built differently: it is a chain of nodes, and each node knows only the next one. You can walk it only forward, and you don't know its length in advance. So counting "from the end" is awkward.

The simple fix takes two passes. The first pass counts the nodes. The second walks to position length - n. In this lesson you do the same in one pass. Two pointers help again, as when you found the middle of a list. This time they move at the same speed and keep a fixed distance between them.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Linked list problems that count from the end of the list, or need two spots a known distance apart. Move one pointer n steps ahead, then walk both until the front one runs out.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy