Problem 257221 · medium · Phase 02 Linear Data Structures

Candy Crush Row

stacks · strings · run-length

A row of candies is given as a string s of lowercase letters. Whenever k adjacent equal candies appear they are removed, the row closes up, and the check repeats until no group of k adjacent equal candies remains. Return the final row.

Examples

Input:  s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: "deeedbbcccbdaa" -> "ddbbcccbdaa" -> "ddbbbdaa" -> "dddaa" -> "aa".

Input:  s = "pbbcggttciiippooaais", k = 2
Output: "ps"

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…