Problem Statement
Decode String
You are given a short, coded string and you need to spell it out in full. The code works like this: k[stuff] means "take stuff and write it out k times in a row." So 3[a] means "write a three times," which is aaa. The catch is that codes can sit inside other codes, like 3[a2[c]], and you have to unpack the inside one before you can finish the outside one. The perfect tool here is a stack. A stack is like a pile of plates: you add a plate to the top, and when you take one, you take it from the top, so the last plate you put on is the first one you take off. That fits this problem because the most recently opened bracket is always the first one that should close, which is exactly how the pile of plates behaves. Every time we open a bracket, we set the outer work aside on the pile, do the inner work fresh, then take the outer work back off the pile and glue the pieces together.
Signals to notice
Brute force first
No simpler alternative — the nesting requires structured parsing. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Stack: push characters until ']'. On ']': pop until '[' to get the string, pop to get the number, repeat the string that many times, push back. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on s = "3[a2[c]]"
'3' → digit: num=3 (cur="", stack=[])
'[' → push("",3): stack=[("",3)], cur="", num=0
'a' → letter: cur="a" (num=0)
'2' → digit: num=2 (cur="a")
'[' → push("a",2): stack=[("",3),("a",2)], cur="", num=0
'c' → letter: cur="c"
']' → pop("a",2): cur="a"+"c"*2="acc", stack=[("",3)]
']' → pop("",3): cur=""+"acc"*3="accaccacc" → return "accaccacc"What must stay true
The stack naturally handles nesting — inner brackets are resolved first. When you hit ']', everything since the last '[' is the string to repeat. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
stack = []; cur = ""; num = 0 for ch in s: if digit: num = num*10 + ch # multi-digit safe elif '[': push(cur, num); cur="" ; num=0 elif ']': prev, k = pop(); cur = prev + cur*k else: cur += ch return cur
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Multi-digit numbers — '12[a]' means repeat 'a' 12 times, not '1' followed by '2[a]'. Parse the full number before pushing. The fix is usually to return to the meaning of each move, not just the steps themselves.