Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Decode a string where k[s] means s repeated k times (brackets can nest).

Problem: Decode a string where k[s] means s repeated k times (brackets can nest).
def decode(s):
    st, cur, k = [], "", 0
    for c in s:
        if c.isdigit(): k = k * 10 + int(c)
        elif c == '[': st.append((cur, k)); cur, k = "", 0
        elif c == ']':
            prev, n = st.pop(); cur = prev + cur * n
        else: cur += c
    return cur
print(decode("2[ab3[c]]x"))
What is printed?
  1. A. abcabcabcx
  2. B. abcccabcccx
  3. C. abcccx
  4. D. abcccabcccxx

Correct answer: B. abcccabcccx

The inner 3[c] becomes 'ccc', so 2[abccc] becomes 'abcccabccc', and the trailing x is appended once: 'abcccabcccx'. The stack stores the text built before each '[' with its multiplier.

More Coding Interview Problems questions

Exams that ask this topic