Eager Deletion of Repeated Character Blocks
Stacks & QueuesAuto-graded · 22 test casesLast updated
Scan a string and delete each block of k equal adjacent characters as soon as it forms, handling cascading merges with a run-length stack.
You are given a string s and an integer k (k >= 2). Build a result string by reading s from left to right, one character at a time, using this rule:
- Append the current character to the end of the result built so far.
- Look at the maximal block of identical characters at the very end of the result. If that block has length at least
k, delete the block from the result. Because the check runs after every single append, a block is deleted the moment it reaches length exactlyk. - After a deletion, the characters on either side of the removed block become adjacent. They may later merge into a new block, which is checked by the same rule as more characters arrive.
Characters that arrive after a deletion start counting from zero for that block. For example, with k = 3, the string "bbbb" becomes "b": the first three b characters are deleted together, and the fourth one is kept.
Return the final result string after all characters of s have been processed. The result can be empty.
Function
Implement collapse_runs(s, k), which returns the final string.
Constraints
0 <= len(s) <= 10^52 <= k <= 10^5sconsists of arbitrary characters, and equality is case-sensitive.- Your solution should run in
O(n)time andO(n)extra space.
Examples
Example 1
Input: collapse_runs('abbbbc', 3)
Output: 'abc'
Example 2
Input: collapse_runs('aaabbbcc', 3)
Output: 'cc'
Example 3
Input: collapse_runs('baaabbbaac', 2)
Output: 'babc'
Hints
Hint 1
Process the input one character at a time. After each append, only the end of the current result can possibly contain a block that needs deleting.
Hint 2
Instead of storing individual characters, keep a stack of (character, count) pairs, one per block of identical adjacent characters.
Hint 3
When you delete the top block, the pair underneath is exposed. If the next character equals it, extend that pair instead of pushing a new one. This handles cascading merges automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan s left to right while keeping a stack of [character, count] pairs. The stack describes the result built so far, grouped into blocks of identical adjacent characters.
For each incoming character ch:
- If the stack is non-empty and the top pair has the same character, increment its count.
- Otherwise, push
[ch, 1]. - If the top pair's count is now at least
k, pop it.
At the end, expand each pair back into character * count and join the pieces.
Why it works
The stack maintains two invariants after every step:
- Adjacent pairs have different characters. We only push when the character differs from the top. After a pop, the exposed pair was already different from the removed one. If the next character matches the exposed pair, we merge into it rather than push.
- Every pair has count
< k. Any pair that reacheskis popped immediately.
So the stack is always the fully reduced result for the prefix processed so far. A new character can only change the last block, so checking only the top is enough. Cascades need no special handling. When a block is deleted, the block beneath it becomes the top, and the next matching character extends it. If that extension reaches k, it is popped in turn.
Example with k = 3 and "abbbaa": after a, b, b, b the stack is [a1, b3], and the b block is popped, leaving [a1]. The next two a characters make [a3], which is popped as well, so the result is "".
Complexity
- Time:
O(n). Each character costs a constant number of operations (one comparison, one increment or push, at most one pop), and the final join outputs at mostncharacters. - Space:
O(n). In the worst case, such as when no adjacent characters repeat, the stack holds one pair per character.
Reference solution
def collapse_runs(s: str, k: int) -> str:
# Each entry is [character, block length] for the reduced string so far.
stack = []
for ch in s:
if stack and stack[-1][0] == ch:
stack[-1][1] += 1
else:
stack.append([ch, 1])
if stack[-1][1] >= k:
stack.pop()
return ''.join(ch * count for ch, count in stack)