Remove Nth Node From End of List

Unlink the node that sits n places from the end of a linked list, walking the list only once.

Given the first node (the head) of a linked list and a number n, remove the node that is n-th from the end, counting the last node as 1, and return the head of the changed list. n is always between 1 and the length of the list. Try to do it in one pass over the list.

Example 1
Input: head = [1, 2, 3, 4, 5], n = 2
Output: [1, 2, 3, 5]
Example 2
Input: head = [1], n = 1
Output: []
Example 3
Input: head = [1, 2], n = 2
Output: [2]
Explanation: the head itself is removed.
Solution

The Idea

A linked list is like a treasure hunt. Each clue tells you where the next one is, and you only learn the way by following the clues one at a time. In a linked list, each item is a node that holds a value and a next link to the node after it. The last node's next is null, meaning there is nothing after it.

Take Example 1, the list 1, 2, 3, 4, 5 with n = 2. Counting from the end, 5 is first and 4 is second, so 4 has to go. Removing it does not mean deleting anything: node 3's next simply changes from 4 to 5, and anyone walking the list now skips 4. So the node we really need to reach is 3, the one just before the node to remove.

That raises the real question. Standing at the head, how do we know that 3 is the one, without first walking to the end to count the nodes? A node cannot tell how far it is from the end.

Two markers walking the list can tell. Call them lead and trail. Send lead ahead first, then move both one node at a time. The gap between them never changes, so when lead runs off the end, trail is a known distance from the end. Look at the picture below.

The list dummy, 1, 2, 3, 4, 5 with n = 2. First lead moves 3 steps to node 3 while trail stays on dummy. Then both move together until lead is null, which leaves trail on node 3, just before node 4, the node to remove. trail.next is changed to point at 5.

Both rows start with an extra node labelled dummy, placed in front of 1, so that even the head has a node before it. In the row labelled "After lead moves n + 1 = 3 steps", trail is still on dummy and lead is on 3. In the second row, both have moved three more times: lead has reached null, and trail stands on 3, right before the node to remove. Changing trail.next to 5 finishes the job.

So the distance from the end is measured by the gap between two markers, not by counting the list first. A pair of markers moving through the same list like this is often called the two-pointer technique.

Solution Approach

Turning that idea into code means comparing it with the slower way of counting first, then settling three things: what to do when the head itself is removed, how big the gap must be, and how to unlink the node.

The two-pass way

Why not count the nodes first? Walk the whole list once to get its length L, then walk again L - n steps to the node before the one to remove. That works, but it reads the list twice. The two markers do the counting while they walk, so the list is read once.

A dummy node in front of the head

What if the node to remove is the head? In Example 3, the list is 1, 2 and n = 2, so 1 goes. There is no node before 1 whose next we could change. A dummy node, an extra node that holds no real value and points at the head, fills that place. Both markers start on it, and dummy.next is the head of the result in every case, even when the old head is gone.

The size of the gap

How far ahead should lead go? When lead is null, it is one place past the last node. The node to remove is n places from the end, counting the last as 1, so it sits n places behind that null. The node before it sits n + 1 places behind. So lead moves n + 1 steps before trail starts moving.

Unlinking the node

Once trail stops, trail.next is the node to remove, and trail.next.next is the node after it, or null if the removed node was the last one. Setting trail.next = trail.next.next skips the node, so walking the list from the head never reaches it again.

Java Solution

The method removeNthFromEnd works in these steps:

  1. First, create the dummy node with new ListNode(0, head), so it points at the head, and start both markers, lead and trail, on it.
  2. Move lead forward n + 1 times with a for loop whose counter i starts at 0 and runs while i <= n.
  3. Then a while loop moves lead and trail one node each, until lead is null.
  4. Now trail is just before the node to remove, so set trail.next = trail.next.next.
  5. Return dummy.next, the head of the changed list.

The class also has a small ListNode class, build to make a list from numbers, and show to print a list in the examples' format. The main method runs the three examples, then removes the last node of the list 1, 2 (n = 1) and the first node of 1, 2, 3, 4, 5 (n = 5).

Java
public class RemoveNthNodeFromEndOfList {

    static class ListNode {
        int val;
        ListNode next;

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

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);   // a node in front of the head
        ListNode lead = dummy;
        ListNode trail = dummy;
        for (int i = 0; i <= n; i++) {
            lead = lead.next;                      // n + 1 steps: lead is n + 1 nodes ahead
        }
        while (lead != null) {
            lead = lead.next;
            trail = trail.next;
        }
        trail.next = trail.next.next;              // trail is just before the node to remove
        return dummy.next;
    }

    static ListNode build(int... values) {
        ListNode head = null;
        for (int i = values.length - 1; i >= 0; i--) {
            head = new ListNode(values[i], head);
        }
        return head;
    }

    static String show(ListNode head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode node = head; node != null; node = node.next) {
            sb.append(node.val).append(node.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

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

Running it prints:

Output
[1, 2, 3, 5]
[]
[2]
[1]
[2, 3, 4, 5]

Node 4 is gone from [1, 2, 3, 5], the only node is gone in [], and the old head 1 is gone in [2], just as the three examples expect. The fourth line, [1], comes from removing the last node of 1, 2: trail stops on 1, and trail.next.next is null, so 1 becomes the end of the list.

Look at the last line, [2, 3, 4, 5]. With n = 5 on five nodes, the first loop's six steps take lead from the dummy all the way to null, so the while loop never runs. trail stays on the dummy, and the head is removed, as in Example 3.

The <= in the first loop matters. With i < n, the gap is only n, so trail stops on the node to remove instead of the one before it. Example 1 then prints [1, 2, 3, 4], losing 5 instead of 4. Example 2 fails with a NullPointerException, because trail.next is already null.

Complexity

The work is one walk of lead from the dummy to the end, with trail following behind.

  • Time: O(L), where L is the number of nodes. Across its two loops, lead steps over each node once and then onto null, and trail takes fewer steps than that.
  • Space: O(1). However long the list is, the method adds only the dummy node and the two markers.

Rotate List also needs the node a set distance from the end. There, the nodes are counted first, because the count is needed anyway to shrink a large k.