mediumStringStackStack

Decode String

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

Recognize the pattern

nested encoded stringk[encoded_string] means repeat k timesrecursive structure

Brute force idea

A straightforward first read of Decode String is this: 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.

Better approach

A calmer way to see Decode String is this: 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.

Key invariant

The truth you want to protect throughout Decode String is this: 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.

Watch out for

One easy way to drift off course in Decode String is this: 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