Cascade Removal of Equal Neighbor Groups
Stacks & QueuesAuto-graded · 26 test casesLast updated
Tests stack-based simulation of iterative removals that trigger chain reactions when fragments recombine.
You are given a string text consisting of lowercase English letters and a positive integer threshold.
An elimination removes exactly threshold consecutive identical characters from the string. After an elimination, the portions on either side close together, which may form new sequences of identical neighbors. Continue performing eliminations until no group of threshold or more consecutive equal characters exists.
Return the resulting string after all possible eliminations have been completed.
Rules
- Each elimination deletes exactly
thresholdcharacters, not more. If a sequence contains more thanthresholdidentical characters, onlythresholdare removed per operation, so a sequence of length not divisible bythresholdwill leave a remainder. - After an elimination, the left and right fragments join immediately, potentially creating new sequences eligible for elimination.
- The order in which you choose to eliminate does not affect the final result; the answer is always unique.
- If all characters are eliminated, return the empty string
"".
Constraints
1 <= len(text) <= 10^52 <= threshold <= 10^4textcontains only lowercase English letters'a'through'z'.
Examples
Example 1
Input: cascade_remove('abbbaac', 3)
Output: 'c'
Example 2
Input: cascade_remove('xyyzzzyx', 2)
Output: 'xzyx'
Example 3
Input: cascade_remove('aabbaa', 2)
Output: ''
Hints
Hint 1
Think about how a stack naturally handles the 'join and cascade' behavior when neighbors meet after a removal.
Hint 2
Store both the character and how many times it appears consecutively to avoid rescanning.
Hint 3
When a group reaches the threshold size, remove it entirely from your structure—this automatically exposes what was underneath.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to use a stack that tracks runs of consecutive identical characters along with their counts. Process the input string from left to right, maintaining the fully reduced prefix at each step.
For each incoming character:
- If it matches the character at the top of the stack, increment that run's count. When the count reaches exactly
threshold, pop the entire run—this represents one elimination. - If it differs from the top, push a new run with count 1.
When a run is eliminated (popped), the run beneath it automatically becomes the new top. If subsequent characters match that newly-exposed run, they extend it naturally, implementing the cascade behavior without extra work.
After processing all characters, reconstruct the final string by expanding each (character, count) pair.
Why It Works
The algorithm maintains this invariant after processing each character:
- The stack, when expanded, represents the completely reduced form of the prefix seen so far.
- No run on the stack has a count equal to or exceeding
threshold. - Adjacent runs always have different characters.
Each operation preserves these properties:
- Appending a different character creates a run of size 1, which cannot be eliminated since
threshold >= 2. - Extending a matching run only affects the topmost run. If it reaches
threshold, immediate removal is exactly one valid elimination. - After a pop, the newly exposed run has no characters to its right yet, so it can only merge when a future matching character arrives—which the "extend" branch handles automatically.
Because the problem guarantees uniqueness regardless of elimination order, performing each elimination the instant a run reaches threshold produces the correct final result.
For sequences longer than threshold: each time the count hits threshold the run is popped, and the next identical character starts a fresh run. This correctly leaves length % threshold characters.
Complexity
- Time: O(n) where n is the length of the input. Each character is pushed once and popped at most once. Rebuilding the output is O(n) since the sum of all counts cannot exceed n.
- Space: O(n) in the worst case when no eliminations occur and every character forms its own run or extends one.
Using counts is crucial: a plain character stack would require scanning back threshold - 1 positions on each push to detect a removable group, degrading to O(n × threshold).
Full Solution
def cascade_remove(text: str, threshold: int) -> str:
chars = []
counts = []
for ch in text:
if chars and chars[-1] == ch:
counts[-1] += 1
if counts[-1] == threshold:
chars.pop()
counts.pop()
else:
chars.append(ch)
counts.append(1)
return ''.join(c * n for c, n in zip(chars, counts))