Remove Nth Node From End of List
Problem Statement
Given the head
of a linked list, remove the n-th
node from the end of the list and return its head.
Example
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
The 2nd node from the end (value 4) is removed.
Constraints
- • The number of nodes in the list is sz.
- • 1 <= sz <= 30
- • 0 <= Node.val <= 100
- • 1 <= n <= sz
Solutions
Approach 1: Two-Pass Algorithm
A straightforward but less efficient approach is to traverse the linked list twice. The first pass is to determine the total number of nodes (the length of the list), and the second pass is to locate and remove the nth node from the end.
Algorithm Steps
- First Pass: Traverse the entire list to count the total number of nodes, let's call it
length
. - Calculate the position of the node to remove from the beginning:
target_index = length - n
. - Handle the edge case where the head node needs to be removed (i.e.,
target_index === 0
). - Second Pass: Traverse the list again up to the node just before the target node (at
target_index - 1
). - Update the
next
pointer of this preceding node to skip the target node, effectively removing it.
While this method is easy to understand, its main drawback is the need for two full traversals of the list, making it less optimal than a single-pass solution.
Approach: Two Pointers
The optimal solution uses a two-pointer technique to find the nth node from the end in a single pass. This avoids the need to first traverse the list to find its length.
Algorithm Steps
- Initialize two pointers,
slow
andfast
, at the head of the list. - Move the
fast
pointern
steps ahead. - If
fast
becomes null, the head is the node to be removed. - Move both
slow
andfast
one step at a time untilfast
reaches the last node. - The
slow
pointer will now be at the node just before the one to be removed. - Update
slow.next
to skip the target node.