You're given a singly linked list. Your task is to remove the nth node from the end and return the updated head of the list.
💡 Approach
To solve this efficiently in one pass, we use the two-pointer technique:
-
Dummy Node:
- Add a dummy node pointing to the head. This simplifies edge cases like removing the first node.
-
Two Pointers:
- Initialize two pointers:
left
at the dummy node andright
at the head. - Move
right
ahead byn
steps. This ensures the gap betweenleft
andright
isn
nodes. - Now, move both
left
andright
one step at a time untilright
reaches the end of the list.
- Initialize two pointers:
-
Remove the Node:
- At this point,
left.next
points to the node that needs to be removed. - Update
left.next = left.next.next
to skip the nth node.
- At this point,
-
Return:
- Return
dummy.next
which is the new head of the modified list.
- Return
Diagrams
✅ Code (JavaScript)
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function (head, n) {
let dummy = new ListNode(0, head); // Step 1: Dummy node
let left = dummy;
let right = head;
// Step 2: Move right n steps ahead
while (n > 0 && right) {
right = right.next;
n--;
}
// Step 3: Move both pointers until right reaches the end
while (right) {
left = left.next;
right = right.next;
}
// Step 4: Remove the nth node
left.next = left.next.next;
return dummy.next;
};
⏱️ Time & Space Complexity
-
Time Complexity:
O(L)
-
L
is the number of nodes in the list. - We make a single pass through the list using the two-pointer technique.
-
-
Space Complexity:
O(1)
- No extra space is used apart from a few pointers.