input3[a2[c]]layoutouter to innercurrent""repeat3action0 * 10 + 3
Save the outer contextAt the first [, push ("", 3), then reset current="" and repeat=0.
("", 3)top saved context
input3[a2[c]]layoutouter to innercurrent""repeat0actionpush and reset
Build outer textReading a appends it to the current nesting level: "" + "a" = "a".
("", 3)top saved context
input3[a2[c]]layoutouter to innercurrent"a"repeat0actionappend a
Build the inner countReading digit 2 applies repeat = 0 * 10 + 2 = 2 while current stays "a".
("", 3)top saved context
input3[a2[c]]layoutouter to innercurrent"a"repeat2action0 * 10 + 2
Save the nested contextAt the second [, push ("a", 2), then reset current="" and repeat=0.
("", 3)("a", 2)top saved context
input3[a2[c]]layoutouter to innercurrent""repeat0actionpush and reset
Build the inner textReading c appends it to the empty inner string, producing current="c".
("", 3)("a", 2)top saved context
input3[a2[c]]layoutouter to innercurrent"c"repeat0actionappend c
Close the inner repeatThe first ] pops ("a", 2): "a" + "c" * 2 = "acc".
("", 3)top saved context
input3[a2[c]]layoutouter to innercurrent"acc"repeat0action"a" + "c" * 2
Close the outer repeatThe final ] pops ("", 3): "" + "acc" * 3 = "accaccacc".
emptytop saved context
input3[a2[c]]layoutouter to innercurrent"accaccacc"repeat0action"" + "acc" * 3resultaccaccacc
Recognize it
Use a context stack when repeat counts and bracketed substrings can nest, so finishing an inner region must resume text and count saved before its opening bracket.
Keep true
Before each character, current is the decoded text for the active nesting level, repeat is the number parsed immediately before its next [, and every stack entry preserves one suspended outer (text, count) pair.
Reuse it
When nested work temporarily replaces an outer accumulator, push exactly the outer state needed to resume it; this transfers to expression evaluation, nested tags, and recursive-descent simulation.
Read it this way: Before scanning 3[a2[c]], stack=[], current="", and repeat=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Stack for nested state.
Simple idea: At [, save the text and repeat count built so far. Start a new inner
string. At ], finish the inner string and attach it to the saved outer string.
def decode_string(text: str) -> str: stack: list[tuple[str, int]] = [] current = "" repeat = 0 for char in text: if char.isdigit(): repeat = repeat * 10 + int(char) elif char == "[": stack.append((current, repeat)) current, repeat = "", 0 elif char == "]": previous, count = stack.pop() current = previous + current * count else: current += char return current
Cost:O(n+m) time and O(n+m) space, where m is the output length.