Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Decode a string like 3[a2[c]] where k[...] repeats the bracket content k times.

Problem: Decode a string like 3[a2[c]] where k[...] repeats the bracket content k times.
def decode(s):
    st, cur, k = [], '', 0
    for ch in s:
        if ch.isdigit(): k = k * 10 + int(ch)
        elif ch == '[': st.append((cur, k)); cur, k = '', 0
        elif ch == ']':
            prev, n = st.pop(); cur = prev + cur * n
        else: cur += ch
    return cur
print(decode("3[a2[c]]"), decode("2[ab]3[x]y"), len(decode("10[a]")))
What is printed?
  1. A. acacac ababxxxy 10
  2. B. accaccacc ababxxxy 10
  3. C. accaccacc abxxxy 10
  4. D. accaccacc ababxxxy 1

Correct answer: B. accaccacc ababxxxy 10

Push the string built so far and the repeat count at '['; at ']' repeat the inner string and append it to the saved prefix. 2[c] → cc, a + cc = acc, ×3. Counts can have several digits (10). Output-size bound: O(length of the result).

More Coding Interview Problems questions

Exams that ask this topic