Data Structures & AlgorithmsHardProduct company OA

Problem: A candy-crush style cleaner repeatedly deletes any k equal adjacent letters (cascading) until none remain. A stack of (letter, run length) does it in one pass.

Problem: A candy-crush style cleaner repeatedly deletes any k equal adjacent letters (cascading) until none remain. A stack of (letter, run length) does it in one pass.
def crush(s, k):
    st = []
    for c in s:
        if st and st[-1][0] == c:
            st[-1][1] += 1
            if st[-1][1] == k: st.pop()
        else:
            st.append([c, 1])
    return "".join(c * n for c, n in st)
print(crush("abbbaacccad", 3), crush("xyyxxyyy", 2))
What is printed?
  1. A. ad x
  2. B. ad xy
  3. C. aaad y
  4. D. aad xy

Correct answer: B. ad xy

When a run reaches k it is popped, which can make the letters on either side adjacent and merge their runs (cascade). "abbbaacccad": bbb vanishes, leaving a + aa = aaa, which vanishes; ccc vanishes; a, d remain → "ad". "xyyxxyyy": yy vanishes, x + x vanishes, then x, yy vanishes, y → "xy". Repeated string scanning is O(n²/k); the stack is O(n).

More Coding Interview Problems questions

Exams that ask this topic