Medium dsa linked-lists

Remove Nth Node From End of List

The 30 second answer

I put a dummy head in front, then send a fast pointer n + 1 steps ahead of a slow pointer. When fast reaches the end, slow sits just before the node I need to drop, so I can skip it. The dummy head means deleting the original head needs no special case.

Could you say this in an interview?

Problem Given the head of a list, remove the n-th node from the end and return the new head. n is guaranteed to be a valid count. Original: LeetCode 19: Remove Nth Node From End of List.

Understanding the prompt You do not know the length in advance if you want a true one-pass solution. Removing the first node (when n equals the length) must work, which is why a dummy head is useful. The problem guarantees n is in range.

Pattern recognition A dummy head plus two pointers a fixed gap apart, which is a close cousin of fast and slow pointers.

Brute force Count the length in one pass, then walk length - n steps in a second pass and splice. That is two passes and still O(1) space.

Optimal dummy.next = head. Advance fast n + 1 steps from dummy, then walk fast and slow together until fast is null. slow.next is the target; set slow.next = slow.next.next. Return dummy.next. The gap of n + 1, not n, is what leaves slow one node before the victim.

Alternatives The two-pass length version is easier to write if you are short on time. A recursive stack that counts on the way back also works and uses O(n) stack space.

Java solution

public class RemoveNthNodeFromEndOfList {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    static ListNode list(int... a) {
        var dummy = new ListNode(0);
        var t = dummy;
        for (int x : a) {
            t.next = new ListNode(x);
            t = t.next;
        }
        return dummy.next;
    }

    static String str(ListNode h) {
        var sb = new StringBuilder("[");
        for (ListNode p = h; p != null; p = p.next) {
            if (sb.length() > 1) sb.append(", ");
            sb.append(p.val);
        }
        return sb.append("]").toString();
    }

    static ListNode removeNthFromEnd(ListNode head, int n) {
        var dummy = new ListNode(0, head);
        ListNode fast = dummy, slow = dummy;
        for (int i = 0; i < n + 1; i++) fast = fast.next;
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }

    public static void main(String[] args) {
        System.out.println(str(removeNthFromEnd(list(1, 2, 3, 4, 5), 2))); // [1, 2, 3, 5]
        System.out.println(str(removeNthFromEnd(list(1), 1)));              // []
        System.out.println(str(removeNthFromEnd(list(1, 2), 1)));           // [1]
        System.out.println(str(removeNthFromEnd(list(1, 2), 2)));           // [2]
    }
}

Complexity O(L) time for a list of length L, O(1) extra space.

Edge cases

  • Official samples: [1,2,3,4,5] with n = 2 becomes [1,2,3,5]; 1 with n = 1 becomes []; [1,2] with n = 1 becomes 1.
  • n equal to the length, as in [1,2] with n = 2, removes the head and returns [2].

Follow-ups

  • Middle of the Linked List is the same two-pointer idea with a different gap.
  • Delete a node when you are given only that node, not the head: copy the next value and splice, which does not work for the tail.

Tests [1,2,3,4,5] with n=2 becomes [1,2,3,5]. 1 with n=1 becomes []. [1,2] with n=1 becomes 1, and with n=2 becomes [2].

How to say it in the interview "I use a dummy head and two pointers n + 1 apart. When the lead pointer reaches the end, the other is just before the node I need to remove, so I skip it. The dummy head covers the case where I delete the original head. One pass, constant space."

Sources (1)
  1. LeetCode 19: Remove Nth Node From End of Listleetcode.com