Data Structures & Algorithms Linked Lists
💡
Exercise 65

Remove Nth From End 20 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a linked list, remove the nth node from the end and return the head. Do it in one pass.

# 1 → 2 → 3 → 4 → 5, n = 2 # Remove 4 (2nd from end) # Result: 1 → 2 → 3 → 5

The trick: use two pointers with a gap of n nodes between them. When the fast pointer reaches the end, the slow pointer is right before the node to remove.

  • Use a dummy node before head (handles edge cases like removing the head)
  • Move fast pointer n+1 steps ahead
  • Move both pointers until fast reaches None
  • slow.next = slow.next.next (skip the target)
📋 Instructions
Implement `remove_nth_from_end(head, n)` using the two-pointer gap technique. Remove the 2nd node from the end of [1,2,3,4,5] and print the result.
Create dummy→head. Move fast n+1 steps from dummy. Then move both until fast is None. Set slow.next = slow.next.next. Return dummy.next.
🧪 Test Cases
Input
Run your code
Expected
1 2 3 5
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.