Pattern visualizer
Decode String
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. Animated on: s = "3[a]2[bc]" — decode a run-length encoded string where k[substring] means substring repeated k times..
A stack per '[' remembers where to resume
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