Data Structures & AlgorithmsHardProduct Company SDE · stack OA

Problem: What is printed by the stack-based decoder for '3[a2[c]]'? It expands k[s] to s repeated k times.

Problem: What is printed by the stack-based decoder for '3[a2[c]]'? It expands k[s] to s repeated k times.
def decode(s):
    stack = []
    cur, num = '', 0
    for ch in s:
        if ch.isdigit():
            num = num * 10 + int(ch)
        elif ch == '[':
            stack.append((cur, num))
            cur, num = '', 0
        elif ch == ']':
            prev, k = stack.pop()
            cur = prev + cur * k
        else:
            cur += ch
    return cur
print(decode('3[a2[c]]'))
What is printed?
  1. A. aaccc
  2. B. accacc
  3. C. accaccacc
  4. D. acccacc

Correct answer: C. accaccacc

Inner 2[c] gives cc, then a + cc = acc, and repeating three times gives accaccacc. Reversing the repeat order gives the trap acccacc.

More Coding Interview Problems questions

Exams that ask this topic