KatInterview

Cascade Removal of Equal Neighbor Groups

Stacks & QueuesAuto-graded · 26 test cases
MediumAuto-gradedStacks & Queuesstackstringsimulation

Last 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 threshold characters, not more. If a sequence contains more than threshold identical characters, only threshold are removed per operation, so a sequence of length not divisible by threshold will 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^5
  • 2 <= threshold <= 10^4
  • text contains 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.