Problem in simple words
Given an encoded string like "3[a]2[bc]", decode it by expanding each bracketed segment its given number of times.
Core idea
Nested encoded strings need a stack because the innermost segment finishes first.
How the algorithm thinks
- 1
Build up the current segment and repeat count
VISITCharacters and digits accumulate into the current segment and count until a bracket changes context.
Watch: The current segment text and accumulated count.
- 2
Save context when a new segment opens
PUSHEntering a new bracket means the enclosing prefix and count need to be remembered for later.
Watch: What's pushed onto the prefix and count stacks.
- 3
Expand and restore context when a segment closes
POPClosing a bracket means the just-finished segment can now be repeated and combined with its saved outer prefix.
Watch: The expanded segment and the restored outer prefix.
- 4
Return the fully decoded string
RETURNOnce every bracket has been matched and expanded, the current segment holds the complete decoded string.
Watch: The final decoded string.
Step-by-step logic
- -Scan the encoded string one character at a time, tracking a current decoded segment and an accumulating repeat count.
- -On a digit, add it to the current repeat count (to handle multi-digit numbers).
- -On '[', push the current count and prefix onto separate stacks, then reset the current segment and count.
- -On ']', pop the saved count and prefix, and set the current segment to the saved prefix plus the current segment repeated that many times; on any other character, just append it to the current segment.
Complexity
Time O(n + output)·Space O(n + output)
the parser scans each token and materializes the decoded output.
Implementation
This is the JavaScript implementation that generates the simulator timeline.
function decodeString(input) {
push count and prefix at '[';
pop and repeat segment at ']';
}Common mistakes
Pause before the next step and name the state change you expect.
Watch the active pointers, discarded range, and output state and match it to the highlighted code line.
Say the rule that never breaks (the invariant) out loud: what remains true before and after this step?
- -Step 1: '3' accumulates the repeat count 3. '[' pushes (count=3, prefix="") and resets current to "".
- -Step 2: 'a' appends to current: current="a". ']' pops (3, ""): current becomes "" + "a".repeat(3) = "aaa".
- -Step 3: '2' accumulates count 2. '[' pushes (count=2, prefix="aaa") and resets current to "". 'b' and 'c' append: current="bc".
- -Step 4: ']' pops (2, "aaa"): current becomes "aaa" + "bc".repeat(2) = "aaabcbc". Final decoded string: "aaabcbc".
- - Decide what each pointer represents.
- - Move the pointer that can safely eliminate work.
- - Keep the invariant true after every move.
Build the reasoning before opening the simulator
Turn the mental model into a short decision checklist, then compare it with the execution timeline.