Back to DSA
Remove Nth Node From End of List
mediumGiven a linked list and an integer n, delete the node that is n positions from the end of the list and return the modified list's head. Aim for a single-pass solution.
Examples
Example 1:
Input:
head = [10,20,30,40,50], n = 3Output:
[10,20,40,50] Example 2:
Input:
head = [7], n = 1Output:
[]Hints
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode fast = dummy, slow = dummy;
for (int i = 0; i <= n; i++) fast = fast.next;
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}Time complexity
O(n)Space complexity
O(1)