Remove Nth Node From End of List
Difficulty: Medium · Pattern: Linked List · LeetCode #19
Remove the n-th node counting from the end of the list (n = 1 is the last node) and return the head. n is always valid. Try to do it in one pass.
Examples
text
1 → 2 → 3 → 4 → 5, n = 2 → 1 → 2 → 3 → 5
1, n = 1 → (empty)
1 → 2, n = 2 → 2Hints
- If one pointer is n nodes ahead of another, when the leader hits the end, the follower is just before the target.
- A dummy node in front of the head handles removing the head itself.
Approach
Put a dummy before the head. Move fast n steps ahead from the dummy, then move fast and slow together until fast.next is null. Now slow.next is the node to delete: slow.next = slow.next.next. Return dummy.next, which also covers the case where the head was removed.
Complexity
Time: O(L), one pass. Space: O(1).
Python solution
def removeNthFromEnd(head, n):
dummy = ListNode(0, head)
slow = fast = dummy
for _ in range(n):
fast = fast.next
while fast.next:
slow, fast = slow.next, fast.next
slow.next = slow.next.next
return dummy.nextJavaScript solution
function removeNthFromEnd(head, n) {
const dummy = new ListNode(0, head);
let slow = dummy, fast = dummy;
for (let i = 0; i < n; i++) fast = fast.next;
while (fast.next) { slow = slow.next; fast = fast.next; }
slow.next = slow.next.next;
return dummy.next;
}