You are given the head of a linked list whose values never go down from one node to the next. Some values may sit in several nodes in a row.
Leave just one node for each value, dropping the extra copies, and return the head of the result. It stays sorted.
Example 1
Input: head = [2, 2, 6] Output: [2, 6] Why: the second 2 is a copy
2 more examples and the constraints
Example 2
Input: head = [1, 4, 4, 4, 9] Output: [1, 4, 9] Why: one 4 stays, the other two go
Example 3
Input: head = [] Output: [] Why: an empty list has nothing to remove
Constraints
- 0 ≤ number of nodes ≤ 300
- −100 ≤ each node value ≤ 100
- The values are in non-decreasing order.
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build a new listO(n)
- Unlink copies in placeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 300 nodes | Verdict |
|---|---|---|---|
| Build a new list | O(n) | Passes; copies every value | |
| Unlink copies in place | O(n) | Best; constant memory |
n = number of nodes. Both read the list once; only the first allocates new nodes.
Edge cases to test
- Empty list. With no head, return null without reading
.next. - One node. A single node has nothing to compare with and comes back as is.
- All values equal. [5, 5, 5, 5] shrinks to [5].
- Copies at the tail. In [1, 3, 3], the last 3 is unlinked and the first 3 points to null.
Common mistakes
- Moving
curforward after every unlink, which leaves copies behind in runs of three or more. - Reading
cur.next.valwithout checking thatcur.nextexists. - Removing every copy of a repeated value, including the first. That is a different problem; here one copy stays.
How to talk through it
- 1Clarify. Does one copy of each value stay? Can the list be empty?
- 2Use the order. Sorted means copies are neighbours, so comparing each node with the next one finds them all.
- 3Code the walk. Unlink when the next value matches, otherwise advance. Say why
curstays after a cut. - 4State the cost. One pass, O(n) time, O(1) extra space, and the head is never replaced.
- 5Test out loud. Run the empty list, a run of three equal values, and copies at the tail.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?