Remove Nth Node From End of List
Problem
Given the
head of a linked list, remove the nth node from the end of the list and return its head.
Examples
Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Remove 4 (2nd from end)
Example 2
Input: head = [1], n = 1
Output: []
Example 3
Input: head = [1,2], n = 1
Output: [1]
Key Insight
Use two pointers with a gap of n nodes. When the fast pointer reaches the end, the slow pointer is at the node before the target.
Create n-step gap between fast and slow. Move both until fast at end. Slow is before target. Delete slow.next.
How to Approach This Problem
Pattern Recognition: When you see keywords like
remove nth node from end of list linked-list,
think Linked List.
Step-by-Step Reasoning
1
A two-pass solution would:
Answer: First count nodes, then remove (n-k+1)th
Count length L, then remove node at position L-n+1 (0-indexed: L-n). This works but requires 2 traversals.
2
If fast is n steps ahead of slow, when fast is at end:
Answer: slow is right before the target node
We want slow to stop at the node BEFORE the target, so we can do slow.next = slow.next.next.
3
To create a gap of n, we:
Answer: Move fast n steps first
Advance fast by n steps. Now fast is n ahead of slow (which is still at start).
4
If we need to remove the head (n equals list length):
Answer: Use a dummy node before head
Dummy node handles edge case. slow.next = slow.next.next works even when target is head.
5
We stop advancing when:
Answer: fast is null
We want slow to be one before target. Stop when fast reaches null.
6
After fast is n ahead, we:
Answer: Move both together until fast is null
Maintain the gap. When fast reaches null, slow is in position.
Solution
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
dummy = ListNode(0, head)
slow = fast = dummy
# Move fast n+1 steps ahead
for _ in range(n + 1):
fast = fast.next
# Move both until fast reaches end
while fast:
slow = slow.next
fast = fast.next
# Remove the nth node
slow.next = slow.next.next
return dummy.next
Complexity Analysis
| Time | O(n) |
|---|---|
| Space | O(1) |
Master This Pattern
Build intuition with interactive MCQs. Practice Linked List problems in the LeetEye app.
Download LeetEye Free