Remove Nth Node From End Of List
Algorithm/TwoPointers
Intuition
To remove the nth node from the end of a linked list, we can use the two-pointer technique. By moving one pointer ahead by n
nodes and then moving both pointers simultaneously, we can position the second pointer at the node just before the one we need to remove.
Approach
Below is the step-by-step breakdown of the approach:
-
Initialize Dummy Node:
- Create a
dummyHead
node that points to thehead
of the list. This helps simplify edge cases, such as when the node to remove is the first node.
- Create a
-
Advance the Fast Pointer:
- Move the
fast
pointern
steps forward. This ensures that whenfast
reaches the end, theslow
pointer will be exactly at the node before the target.
- Move the
-
Move Both Pointers:
- Move
fast
andslow
pointers one step at a time untilfast
reaches the end of the list.
- Move
-
Remove the Target Node:
- Adjust the
next
pointer of theslow
node to skip over the target node.
- Adjust the
-
Return the Result:
- The
dummyHead.next
is the new head of the list, which we return as the final result.
- The
Complexity
- Time complexity: , where is the length of the linked list. We traverse the list twice: once to advance
fast
and once to find the target. - Space complexity: , as only pointers are used for traversal.