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?- A. ad x
- B. ad xy
- C. aaad y
- 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
- Problem: Score a balanced bracket string: "()" = 1, AB = A + B, (A) = 2·A. Each innermost "()" at depth d contributes 2^d. python def…
- Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one…
- Problem: Evaluate an expression of non-negative integers with + − / (no brackets, / truncates toward zero) in one pass with a stack…
- Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the…
- Problem: From a sorted linked list delete EVERY value that occurs more than once (keep only values that appear exactly once). python class…
- Problem: Reorder a list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the second half, then interleave…