DDSA
Advertisement

19. Remove Nth Node From End of List

Time: O(n)
Space: O(1)

Approach

Two pointers spaced n apart. When fast reaches the end, slow is just before the node to remove; update the next pointer.

19.cs
C#
// Approach: Two pointers spaced n apart. When fast reaches the end, slow
// is just before the node to remove; update the next pointer.
// Time: O(n) Space: O(1)

public class ListNode
{
    public int val;
    public ListNode next;
    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}

public class Solution
{
    public ListNode RemoveNthFromEnd(ListNode head, int n)
    {
        ListNode start = new ListNode();
        start.next = head;
        ListNode slow = start;
        ListNode fast = start;
        for (int i = 1; i <= n; i++)
        {
            fast = fast.next;
        }

        while (fast.next != null)
        {
            fast = fast.next;
            slow = slow.next;
        }

        slow.next = slow.next.next;
        return start.next;
    }
}
Advertisement
Was this solution helpful?