Remove Nth Node From End of List - Problem

You're given the head of a singly linked list and need to remove the nth node from the end of the list, then return the modified list's head.

This is a classic linked list manipulation problem that tests your understanding of pointer arithmetic and list traversal techniques. The challenge lies in efficiently locating the nth node from the end without knowing the total length beforehand.

Key Points:

  • The list is 1-indexed from the end
  • You must handle edge cases like removing the head node
  • The solution should work in a single pass for optimal efficiency

Example: If you have [1,2,3,4,5] and n=2, you should remove the 2nd node from the end (value 4), returning [1,2,3,5].

Input & Output

example_1.py โ€” Basic Removal
$ Input: head = [1,2,3,4,5], n = 2
โ€บ Output: [1,2,3,5]
๐Ÿ’ก Note: Remove the 2nd node from the end (node with value 4). The resulting list becomes [1,2,3,5].
example_2.py โ€” Single Node
$ Input: head = [1], n = 1
โ€บ Output: []
๐Ÿ’ก Note: Removing the only node from the list results in an empty list.
example_3.py โ€” Remove Head
$ Input: head = [1,2], n = 2
โ€บ Output: [2]
๐Ÿ’ก Note: Remove the 2nd node from the end, which is the head node (1). The list becomes [2].

Visualization

Tap to expand
Two-Pointer Window TechniqueD12345Sliding Window (Gap = n+1 = 3)SLOWFAST โ†’ nullTARGET TO REMOVEPerfect Gap!๐Ÿ’ก Key Insight: Constant gap ensures perfect positioning!When fast reaches the end, slow is exactly at the removal position
Understanding the Visualization
1
Create the Window
Position two pointers with exactly the right gap between them
2
Slide the Window
Move both pointers together, maintaining the gap
3
Perfect Positioning
When the front reaches the end, the back is exactly where we need it
4
Execute Removal
Remove the target node with a simple pointer update
Key Takeaway
๐ŸŽฏ Key Insight: The two-pointer technique with a fixed gap transforms a two-pass problem into an elegant single-pass solution. This pattern is fundamental to many linked list problems.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the list, visiting each node only once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two pointer variables and one dummy node, constant space

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the list is sz
  • 1 โ‰ค sz โ‰ค 30
  • 0 โ‰ค Node.val โ‰ค 100
  • 1 โ‰ค n โ‰ค sz (n is always valid)
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28 Apple 25
128.4K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen