Remove Nth Node From End of List

MediumLinked lists

You get the head of a singly linked list and a number n. Remove the nth node counting from the end (the last node is the 1st from the end) and return the head of the list that is left.

On this page a list is written as an array of its values, from head to tail, and [] is an empty list.

Examples

Example 1
Input:  head = [3, 6, 9, 12, 15], n = 2
Output: [3, 6, 9, 15]

12 is second from the end, so it goes.

Example 2
Input:  head = [8, 4], n = 2
Output: [4]

The 2nd from the end of a two-node list is the head itself.

Constraints

  • The list has 1 to 30 nodes.
  • 0 ≤ node.val ≤ 100
  • 1 ≤ n ≤ the number of nodes

Stuck?

Hint 1

If one pointer starts n nodes ahead of another and both move together, the back one is n nodes behind the end when the front one gets there.

Hint 2

Start both pointers at a dummy node placed before the head. Then removing the head itself needs no special case, and you return dummy.next.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur