KatInterview

Collapse Repeated Letters: Pair Cancel or Full Run Wipe

Stacks & QueuesAuto-graded · 30 test cases
EasyAuto-gradedStacks & Queuesstackstringsimulation

Last 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^5
  • text contains only lowercase English letters a to z.
  • wipe_runs is True or False.

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.