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:
leftat the dummy node andrightat the head. - Move
rightahead bynsteps. This ensures the gap betweenleftandrightisnnodes. - Now, move both
leftandrightone step at a time untilrightreaches the end of the list.
- Initialize two pointers:
-
Remove the Node:
- At this point,
left.nextpoints to the node that needs to be removed. - Update
left.next = left.next.nextto skip the nth node.
- At this point,
-
Return:
- Return
dummy.nextwhich 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)-
Lis 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.




Top comments (0)