A singly linked list holds distinct values. You are handed one of its nodes, node, but not the head, so you cannot walk to the nodes before it. node is guaranteed not to be the last node.
Change the list so that node's value no longer appears in it: the list gets one node shorter, and every other value keeps its order. Change the list in place; return nothing.
Example 1
Input: head = [6, 2, 8, 3], node = 2 Output: [6, 8, 3] Why: the node holding 2 is handed over and removed
1 more example and the constraints
Example 2
Input: head = [7, -1, 5], node = 7 Output: [-1, 5] Why: the given node can be the head
Constraints
- 2 ≤ number of nodes ≤ 1,000
- −1,000 ≤ each value ≤ 1,000, all values distinct
nodeis in the list and is not the tail
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Shift every value leftO(n)
- Copy the next node, then skip itO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 nodes | Verdict |
|---|---|---|---|
| Shift every value left | O(n) | Correct; rewrites the whole tail | |
| Copy the next node, then skip it | O(1) | Best; two lines |
n = number of nodes from `node` to the end of the list.
Edge cases to test
- Given node is the head. [7, -1, 5] with node 7 becomes [-1, 5]. Nothing special is needed.
- Given node is just before the tail. Its next is the tail, and next.next is null; the skip sets next to null.
- Two nodes only. [1, 2] with node 1 becomes [2].
- The tail is never given. That case is ruled out, and the trick could not handle it: there is no successor to copy.
Common mistakes
- Trying to find the previous node; there is no way back without the head.
- Setting
node = node.next, which only moves a local variable and changes nothing in the list. - Copying the value but forgetting to skip, which leaves two copies of the next value.
How to talk through it
- 1Clarify. Do I get the head? Can the node be the tail? Are values unique? Does deleting mean freeing memory?
- 2Name the obstacle. Unlinking needs the previous node, and there is no way to reach it.
- 3Shift values. Copy each next value back one place and drop the tail. Correct, but O(n).
- 4Copy and skip. Only the first copy matters: take the successor's value, then unlink the successor. O(1).
- 5Test out loud. Run the head, the node before the tail and a two-node list.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?