1604. Crush Equal Runs
A conveyor carries colored tokens, given as a linked list head of integer colors. Whenever a run of equal adjacent colors has length at least k and the next token has a different color (or the belt ends), the whole run is crushed and disappears. The tokens on either side then become neighbours, so equal colors may merge into a new run that can itself be crushed later, causing chain reactions. Runs are always crushed in left-to-right order, so a run that finishes earlier is removed before a later one.
Process the belt from left to right with a stack of (color, count) runs and return the list that remains after everything possible has been crushed, as a new list; return null if nothing remains. Expected cost is O(n) time and O(n) space.
Example 1
- Input:
- head = [1,1,2,2,2,1,3], k = 3
- Output:
- [3]
- Explanation:
The run of 2s is crushed, the 1s merge into a run of three and are crushed too, leaving only 3.
Example 2
- Input:
- head = [4,4,5,6,6], k = 2
- Output:
- [5]
- Explanation:
The 4s and the 6s are both runs of two and vanish, leaving 5.
Constraints
0 ≤ length ≤ 105; 2 ≤ k ≤ 105; colors fit in a 32-bit signed integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)