Skip to contentKEEP THE CRAFTTHE SANCTUARY

Remove Nth Node From End

Remove the nth node from the end of a linked list in one pass with two pointers and a dummy head.

The problem

Implement Solution.removeNthFromEnd(head, n). head is the first node of a singly linked list; each ListNode has val and next fields. Remove the nth node counted from the end of the list and return the head of the resulting list. The list has 1 to 30 nodes, each value is between 0 and 100, and 1 <= n <= the number of nodes. Follow-up: can you do it in a single pass over the list?

Starter code

class Solution:
    def removeNthFromEnd(self, head, n):
        pass

Public examples

  1. head = [1, 2, 3, 4, 5], n = 2gives[1, 2, 3, 5]
  2. head = [2, 3, 4], n = 1gives[2, 3]
  3. head = [100], n = 1gives[]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.