Coding Interview PatternsRemove Nth Node From End of List
MediumFast and Slow Pointers

Remove Nth Node From End of List

Explanation & Solution

Description

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Input:head = [1,2,3,4,5], n = 2
0
1
1
2
2
3
3
4
4
5
Output:[1,2,3,5]
0
1
1
2
2
3
3
5

Explanation: The 2nd node from the end is 4. After removing it, the list becomes [1,2,3,5].

Constraints

  • The number of nodes in the list is sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Approach

Fast and Slow Pointers pattern

1. Create a Dummy Node

  • Create a dummy node that points to head.
  • This handles the edge case where the head itself needs to be removed (e.g., removing the nth node when n equals the list length).

2. Advance the Fast Pointer

  • Move fast forward by n + 1 steps from the dummy node.
  • This creates a gap of n nodes between fast and slow.

3. Move Both Pointers Together

  • Move both slow and fast one step at a time until fast reaches null.
  • At this point, slow is positioned right before the node to be removed.

4. Remove the Target Node

  • Set slow.next = slow.next.next to skip over the nth node from the end.
  • This effectively removes it from the linked list.

5. Return the Result

  • Traverse the modified list starting from dummy.next and collect values into an array.
  • Return the array.

Key Insight

  • The two-pointer technique with an n-step gap lets us find the nth node from the end in a single pass.
  • The dummy node eliminates special-case logic for removing the head.
Time
O(L) where L is the length of the list — one pass.
Space
O(1)only pointer variables are used (excluding the output array).

Visualization

Input:
Linked List Traversal
1021324354null

Press play to start traversal

Slow (S)Fast (F)Both
6 steps

Solution Code