mediumStringStackStack

Decode String

mediumTime: O(n * maxK)Space: O(n * maxK)

Signals to notice

nested encoded stringk[encoded_string] means repeat k timesrecursive structure

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.

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.

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.

Stack Pattern