← Questions
Remove runs of repeated characters (1D candy crush)
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Sep 2025. It tests stacks and strings.
Repeatedly delete runs of equal adjacent characters from a string until none is left, and return what remains. A whole run goes, not just part of it. Deleting a run can join the characters on either side into a new run, which may then be deleted too.
Part 1: runs of two or more
-
crush(s: str) -> str—sholds lowercase letters. While any run of two or more equal adjacent characters exists, delete the leftmost such run. Return the final string.
crush("abbbaaccz") -> "z" # bbb goes, a + aa become aaa and go, then cc goes
crush("abba") -> "" # bb goes, then aa
crush("aabccbd") -> "d"
crush("abcd") -> "abcd"
Part 2: runs of at least k
-
crush_k(s: str, k: int) -> str— the same, for runs of lengthkor more,k >= 2.
crush_k("abbbbc", 3) -> "ac" # all four b's go, not just three
crush_k("deeedbbcccbdaa", 3) -> "aa" # eee, then ccc, then bbb, then ddd
Constraints
-
1 <= len(s) <= 10^5. Aim for O(n) time and O(n) space.
Clarifying questions
- Does a run of
k + 1lose all its characters, or exactlykof them? - Are runs removed one at a time (leftmost first) or all at once? Can the result differ?
- Can the input be empty?
What a strong answer covers
- A stack of
(character, count)pairs. When a different character arrives and the top run is at leastklong, pop it, and the new character may then extend the run below. Pop a long run left on top at the end. - Why one pass gives the same result as deleting the leftmost run over and over, and why the process terminates.
- O(n) time and space, compared with the O(n²) rescan approach.
- Tests: an empty result, nothing to delete, cascades several levels deep, runs exactly
klong and longer.
Follow-ups
- Characters arrive one by one as a stream. Keep the current result up to date.
- Delete exactly
kcharacters at a time instead of the whole run. - Return how many deletions happened in total.
Where it's asked
- Meta · Technical phone screen · Last asked Sep 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
stacks · strings
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
