Remove Nth Node From End of List

Medium

Topics
Linked ListTwo Pointers

Given the head of a linked list, remove the k-th node from the end and return the head. (LeetCode calls this parameter n.)

Example 1

1234removed5null
The 2th node from the end is index 3 from the front. Finding it without a length pass is the point: start one pointer 2 steps ahead, then move both together so that when the leader hits the end the trailer is one before the target.
Linked list values from head to tail.
Input:  head = [1,2,3,4,5], k = 2
Output: [1,2,3,5]

Example 2

1removednull
Input:  head = [1], k = 1
Output: []

Constraints

  • 1 <= number of nodes <= 30
  • 1 <= k <= number of nodes
Editorial — intuition, approach, complexity and pitfalls

Intuition

To find the node k-from-the-end in one pass, keep two pointers k apart. When the leading one falls off the end, the trailing one sits just before the target.

Approach

  1. Use a dummy before the head so removing the first node is uniform.
  2. Advance a fast pointer k steps, then move fast and slow together until fast reaches the end.
  3. slow.next is the node to remove; relink around it.

Dry Run

list 1 -> 2 -> 3 -> 4 -> 5,  k = 2
A dummy node sits in front of the head, and both pointers start there.
  advance fast twice           fast on 1, then on 2
  the gap is now exactly k = 2
  move both   slow on 1   fast on 3
  move both   slow on 2   fast on 4
  move both   slow on 3   fast on 5
  fast.next is null, so fast is at the tail
  slow is therefore k steps back, sitting just BEFORE the node to remove (the 4)
  slow.next = slow.next.next
answer 1 -> 2 -> 3 -> 5
One pass, no length count. Fixing the gap at k and then sliding both pointers
until the leader hits the end leaves the follower exactly where it is needed --
the arithmetic is done by the geometry rather than by subtracting from a length.
The dummy is what makes removing the HEAD an ordinary case. On [1] with k = 1 the
node to delete is the head itself, and slow is still the dummy when the loop ends,
so the same single assignment handles it -- the answer is the empty list. Start
both pointers at `head` instead and that case dereferences null: [1] with k = 1
raises AttributeError, and so does [1,2] with k = 2.

Complexity

  • Time — O(n): a single two-pointer pass.
  • Space — O(1): two pointers.

Common Pitfalls

  • Use a dummy node so removing the head (k == length) needs no special case.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def removeNthFromEnd(self, head, k):
        dummy=ListNode(0,head); fast=slow=dummy
        for _ in range(k): fast=fast.next
        while fast.next:
            fast=fast.next; slow=slow.next
        slow.next=slow.next.next
        return dummy.next
SensAI
Beta
Tap the mic to stop voice mode