Decode String
A stack per '[' remembers where to resume
The tricky part is NESTED brackets — 3[a2[c]] needs the inner expansion done first. A stack solves this the same way it solves any nested-structure problem: every '[' saves the current progress (the count and the string built so far) and starts a fresh scope; every ']' pops that saved state, repeats what was just built, and glues it onto what came before — naturally unwinding the nesting from the inside out.
Details
Animated on: s = "3[a]2[bc]" — decode a run-length encoded string where k[substring] means substring repeated k times.
Problem:Decode StringMedium
A stack per '[' remembers where to resume
step 1 / 9
s="3[a]2[bc]". A stack handles the nesting: when we hit '[', push the current count + string-so-far and start fresh; when we hit ']', pop and repeat.
1FUNCTION decodeString(s):2 countStack, stringStack are empty stacks; current = '', num = 03 FOR each character ch in s:4 IF ch is a digit: num = num*10 + ch5 ELSE IF ch is '[': push num and current onto the stacks; reset current to '' and num to 06 ELSE IF ch is ']': pop the saved count and string; current = savedString + current repeated count times7 ELSE: append ch to current8 RETURN current
← / → step · space play · Home restart
Every step in words
Show all 9 steps
- s="3[a]2[bc]". A stack handles the nesting: when we hit '[', push the current count + string-so-far and start fresh; when we hit ']', pop and repeat.
- '[' at count=3: push (count=3, string="") onto the stack, reset current string.
- Letter 'a': append to current string -> "a".
- ']': repeat "a" x3 and prepend the saved outer string "" -> "aaa".
- '[' at count=2: push (count=2, string="aaa") onto the stack, reset current string.
- Letter 'b': append to current string -> "b".
- Letter 'c': append to current string -> "bc".
- ']': repeat "bc" x2 and prepend the saved outer string "aaa" -> "aaabcbc".
- Input fully consumed. Decoded string: "aaabcbc".
Now solve it yourself
Watching is the first half. The second is writing it without the animation.