KatInterview

Eager Deletion of Repeated Character Blocks

Stacks & QueuesAuto-graded · 22 test cases
MediumAuto-gradedStacks & Queuesstackstringrun-length

Last 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:

  1. Append the current character to the end of the result built so far.
  2. 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 exactly k.
  3. 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^5
  • 2 <= k <= 10^5
  • s consists of arbitrary characters, and equality is case-sensitive.
  • Your solution should run in O(n) time and O(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.