Back to DSA

Remove Nth Node From End of List

medium
Acceptance: 46%
Linked List

Given 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 = 3
Output:[10,20,40,50]
Example 2:
Input:head = [7], n = 1
Output:[]

Hints

00:00
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 complexityO(n)
Space complexityO(1)