Remove Nth Node From End of List - Problem

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

The list is 1-indexed from the end, meaning the last node is the 1st node from the end, the second-to-last is the 2nd node from the end, and so on.

Follow up: Could you do this in one pass?

Input & Output

Example 1 — Remove Middle Node
$ Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
💡 Note: Remove the 2nd node from the end, which is node 4. The 2nd from end (n=2) is at position 4 (1-indexed), so we remove it and return [1,2,3,5].
Example 2 — Remove Head
$ Input: head = [1], n = 1
Output: []
💡 Note: There's only one node and we need to remove the 1st (and only) node from the end. Result is an empty list.
Example 3 — Remove Last Node
$ Input: head = [1,2], n = 1
Output: [1]
💡 Note: Remove the 1st node from end (which is the last node). Remove node 2 and return [1].

Constraints

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

Visualization

Tap to expand
Remove Nth Node From End of List INPUT Linked List: 1 2 3 4 5 2nd from end 1st from end Input Values: head = [1,2,3,4,5] n = 2 Two Pointer Technique Fast Slow ALGORITHM STEPS 1 Initialize Pointers Create fast and slow at head 2 Advance Fast by N Move fast pointer n steps ahead 3 Move Both Together Until fast reaches end 4 Remove Target Node Skip slow.next in the list Pointer Movement: 1 2 3 slow 4 remove 5 fast null skip Time: O(n) | Space: O(1) FINAL RESULT Modified Linked List: 1 2 3 5 4 Removed Output: [1, 2, 3, 5] OK - One Pass! Key Insight: The two-pointer technique maintains a gap of n nodes between fast and slow pointers. When fast reaches the end (null), slow is exactly at the node BEFORE the one to remove. This allows single-pass O(n) solution without knowing the list length beforehand. TutorialsPoint - Remove Nth Node From End of List | Optimal Solution (Two Pointers)
Asked in
Amazon 45 Microsoft 38 Google 32 Facebook 28
280.5K Views
High Frequency
~15 min Avg. Time
8.5K 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