The input is head, the first node of a linked list, and a number, n. Remove the nth node counting from the end of the list. Return the head of the list that remains, or null if no node remains. Try to do it in a single pass.
Examples
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: removing the head is the case that breaks pointer-only solutions.
Example 4:
Input: head = [1,2], n = 1
Output: [1]
Constraints
1 <= list length <= 30
1 <= n <= list length
0 <= Node.val <= 100
Prerequisites
Linked lists — a node holds a value and a next reference, and rearranging a list means moving references, never values. Dummy heads: a node in front of the list so the first element stops being a special case. Two pointers on a list — one ahead of the other, or one moving twice as fast.
How to think about it
1. Two Pointers, n Apart Optimal
Intuition
Counting from the end is counting from the start once you know the length — but the follow-up asks for one pass, and a gap of n does it: send one pointer ahead by n, then move both until the leader falls off. The trailer is now exactly one node before the target. Starting the trailer at a dummy head makes deleting the actual head the same move as any other, which is the case that breaks solutions that skip it.
Algorithm
1. Put a dummy node in front; trail starts on it, lead at head. 2. Advance lead n steps: n nodes now stand between them. 3. Move both until lead is null. 4. Unlink the node after trail. 5. Return dummy.next.
Time & Space
Time O(L) in one pass, L the number of nodes. Space O(1).
2. Count the Length First
Intuition
The nth node from the end comes after the first length - n nodes, once the length is known. So one pass counts the nodes, and a second walks from a dummy in front of the head length - n steps, which ends on the node just before the one to remove, and unlinks the node after it. When n is the length, that is no steps at all, and the node unlinked is the head: the dummy makes removing the head the same move as any other. It reads the list twice, where the follow-up asks for one pass.
Algorithm
1. Walk the list once, counting its nodes: the length. 2. Put a dummy node in front, and start before on it. 3. Advance before length - n steps: it stops on the node before the one to remove. 4. Unlink the node after before. 5. Return dummy.next.
Time & Space
Time O(L) in two passes, L the number of nodes. Space O(1).