Stack · Medium
A token-cleanup rule removes exactly k consecutive equal tokens at a time. Removing a group can bring matching tokens together and trigger another removal. The cleanup must preserve the order of all surviving tokens and run efficiently on a long sequence.
Process the sequence from left to right and return the survivors after repeatedly deleting each completed group of k equal tokens.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], k: integer }
Fields
- nums contains signed integer token labels.
- k is the positive group size; equality is by numeric value.
Output
Return value
- Return the remaining labels in order. Delete a group immediately when its run reaches k.
- For k = 1 every token is removed. Runs longer than k may leave a remainder.
Constraints
- 0 <= nums.length <= 100000; each value is an integer between -1000000000 and 1000000000.
- 1 <= k <= 100001.
Examples
Example 1
{
"k": 2,
"nums": [
1,
2,
2,
1
]
}Returns
[]Example 2
{
"k": 3,
"nums": [
3,
3,
3,
3
]
}Returns
[
3
]Required complexity
O(n) time and O(n) auxiliary space