Problem 257221 · medium · Level 02 Linear Data Structures

Matching Tiles Vanish

stacks · strings · run-length

In a falling-tile puzzle, a row of coloured tiles is written as the string s of lowercase letters (one letter per colour). As soon as k tiles of the same colour stand side by side, exactly those k tiles vanish (a longer run of that colour loses k tiles and keeps the rest), the gap closes, and this goes on until no k equal neighbouring tiles are left. Return the row that remains.

Examples

Input:  s = "abbbaac", k = 3
Output: "c"
Explanation: "abbbaac" -> "aaac" -> "c".

Input:  s = "xyyyyyx", k = 4
Output: "xyx"
Explanation: four of the five y's are removed; one y stays between the x's.

Constraints

  • 1 <= len(s) <= 10**5
  • 2 <= k <= 10**4
  • Target: O(n) time

Goals

  • Store (character, run length) pairs on a stack
  • Trigger a removal exactly when a run reaches length k
Starting Python…