You are given the head of a singly linked list and a number n. Counting from the back, the last node is number 1, the one before it is number 2, and so on.
Delete node number n counted this way, and return the head of the list that remains. If the list had only that one node, return an empty list.
Example 1
Input: head = [3, 8, 1, 6, 4], n = 2 Output: [3, 8, 1, 4] Why: 6 is second from the back
2 more examples and the constraints
Example 2
Input: head = [7], n = 1 Output: [] Why: the only node is removed
Example 3
Input: head = [2, 9], n = 2 Output: [9] Why: second from the back is the head
Constraints
- 1 ≤ number of nodes ≤ 30
- 0 ≤ each node value ≤ 100
- 1 ≤ n ≤ number of nodes
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count, then walkO(L), two passes
- Two pointers with a gapO(L), one pass
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Nodes visited for a 30-node list | Verdict |
|---|---|---|---|
| Count, then walk | O(L) | Passes; two passes | |
| Two pointers with a gap | O(L) | Best; one pass |
L = number of nodes. Both are linear; the gap version reads the list once.
Edge cases to test
- Only one node. [7] with n = 1 must return an empty list, not crash.
- Remove the head. When n equals the length, the head goes. The dummy node makes this the same as any other case.
- Remove the tail. With n = 1,
slowstops on the second-to-last node and its next becomes null. - Equal values. In [5, 5, 5] you remove a position, not a value. Only one 5 goes.
Common mistakes
- Skipping the dummy node, then crashing or returning the wrong head when the head is the node to delete.
- Off by one on the gap: moving fast n − 1 or n + 1 steps, so slow stops on the target itself or two nodes early.
- Returning the old
headinstead ofdummy.next, which still points at the deleted node when the head was removed.
How to talk through it
- 1Clarify. Is n always between 1 and the length? What do I return if the list becomes empty?
- 2Give the two-pass idea. Count the length, then the target is L − n + 1 from the front. Say it is O(L) but reads the list twice.
- 3Introduce the gap. If fast is n nodes ahead of slow, then when fast hits the end, slow is n nodes from it.
- 4Code it with a dummy. Say why the dummy is there: it gives the head a node before it.
- 5Test out loud. Run [7] with n = 1, and [2, 9] with n = 2, where the head is removed.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?