Collapse Repeated Letters: Pair Cancel or Full Run Wipe
Stacks & QueuesAuto-graded · 30 test casesLast updated
Simulate cascading deletions of equal neighbouring letters with a stack, either cancelling pairs or erasing whole leftmost runs, and return what is left.
You are given a string text made of lowercase letters and a boolean wipe_runs. Keep deleting neighbouring equal letters until no more deletions are possible, then return the string that remains. The flag chooses between two deletion rules.
Definitions
A run is a maximal block of consecutive identical characters. For instance, "abbbac" consists of the runs a, bbb, a, c.
Rules
wipe_runs = False(pair rule): Repeatedly pick two adjacent equal characters and delete both. Stop once no two adjacent characters are equal. The final string does not depend on which pair you pick at each step.wipe_runs = True(run rule): Repeatedly delete the entire leftmost run whose length is at least 2. Stop once every run has length 1. Here the order of deletions affects the answer, so always choose the leftmost such run.- After a deletion, the characters on either side of the removed block become neighbours and may form a new run (or a new equal pair).
- Characters that are never deleted keep their original relative order.
- The result may be an empty string.
Task
Implement collapse_repeats(text, wipe_runs) that returns the final string after all deletions under the selected rule.
Constraints
1 <= len(text) <= 10^5textcontains only lowercase English lettersatoz.wipe_runsisTrueorFalse.
Examples
Example 1
Input: collapse_repeats('abbaca', False)
Output: 'ca'
Example 2
Input: collapse_repeats('abbbac', True)
Output: 'c'
Example 3
Input: collapse_repeats('abbaa', True)
Output: ''
Hints
Hint 1
A brute-force approach that rescans the string after every deletion is O(n^2). Think about a stack that holds the already-settled prefix while you scan left to right.
Hint 2
For the pair rule, compare each new character with the top of the stack: if equal, pop; otherwise push. Cascades happen automatically because a pop exposes an older character.
Hint 3
For the run rule, you cannot delete a run until you see that it has ended. Store (character, count) entries, and when a different character arrives, pop the top entry if its count is at least 2, then check whether the newly exposed entry merges with the new character. Do not forget to handle the final run at the end of input.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both rules are solved with one left-to-right scan that keeps the already-reduced prefix on a stack.
Pair rule. For each incoming character, if it equals the top of the stack, pop the top (an adjacent equal pair is removed); otherwise push it. When a pop exposes an older character, that character becomes the neighbour of the next incoming one, so cascades are handled naturally.
Run rule. A run can only be deleted once we know where it ends, so the stack stores (character, count) entries. For each incoming character ch:
- If
chequals the top character, the run is still growing, so increment its count. - Otherwise the top run is now maximal. If its count is at least 2, pop it. The newly exposed entry may equal
ch; if so, increment that entry's count (they merge) and move on. - If
chjoined nothing, push(ch, 1).
After the loop, the last run is also maximal, so pop it if its count is at least 2.
Why it is correct
Pair rule. Every pop removes two characters that are adjacent in the current string, since everything between them was already deleted. At the end no two neighbouring stack entries are equal, so the stack is fully reduced. The pair-deletion system gives the same result regardless of order, so this is the answer.
Run rule. Invariant: neighbouring stack entries differ, and every entry except possibly the top has count 1. The current string is the stack followed by the unread suffix, so the leftmost run of length at least 2 is either the top run (once it is known to be maximal) or lies in the unread part. The algorithm deletes the top run exactly when it becomes maximal, which is precisely the leftmost-run rule. After the pop, the exposed entry has count 1, so it either merges with ch (count 2, open run) or stays a singleton below the new entry; the invariant holds and no further cascade below is possible.
Trace of "abbaa" with the run rule: [a1], [a1,b1], [a1,b2], then a arrives, so pop b2 and merge with a to get [a2], then [a3], and at the end pop a3, giving "".
Complexity
- Time: O(n), since each character is pushed and popped at most once.
- Space: O(n) for the stack.
Reference solution
def collapse_repeats(text: str, wipe_runs: bool) -> str:
if not wipe_runs:
st = []
for ch in text:
if st and st[-1] == ch:
st.pop()
else:
st.append(ch)
return "".join(st)
chars = []
cnts = []
for ch in text:
if chars and chars[-1] == ch:
cnts[-1] += 1
continue
if cnts and cnts[-1] >= 2:
chars.pop()
cnts.pop()
if chars and chars[-1] == ch:
cnts[-1] += 1
continue
chars.append(ch)
cnts.append(1)
if cnts and cnts[-1] >= 2:
chars.pop()
cnts.pop()
return "".join(chars)