19. Remove Nth Node From End of List
Asked at 16Meta65Amazon53Microsoft53Bloomberg50Google50Apple43Tinkoff75Qualcomm68Morgan Stanley64Accenture61josh technology50tcs46Flipkart43Yandex42Oracle27TikTok26
Problem
Remove the n-th node from the end of a linked list and return the head.
Example: 1→2→3→4→5, n = 2 → 1→2→3→5
Constraints: follow-up: one pass.
Advance fast n steps ahead from a dummy, then move both until fast is last; slow.next is the node to delete.
dummy 1 2 3 4 5, n=2
fast moves 2 ahead; then both move until fast at 5:
slow at 3 -> skip 4 -> 1 2 3 5
Complexity: O(n) time, one pass.
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
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.next
assert list_vals(Solution().removeNthFromEnd(make_list([1, 2, 3, 4, 5]), 2)) == [1, 2, 3, 5]
assert list_vals(Solution().removeNthFromEnd(make_list([1]), 1)) == []
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head), slow = dummy, fast = dummy;
for (int i = 0; i < n; i++) fast = fast.next;
while (fast.next != null) { slow = slow.next; fast = fast.next; }
slow.next = slow.next.next;
return dummy.next;
}
}
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{Next: head}
slow, fast := dummy, dummy
for i := 0; i < n; i++ { // fast runs n nodes ahead
fast = fast.Next
}
for fast.Next != nil {
slow, fast = slow.Next, fast.Next
}
slow.Next = slow.Next.Next
return dummy.Next
}