Expand a valid encoded string whose bracketed pieces may be repeated and nested.
Problem
Input. A valid encoded string text containing literal text and expressions of the form count[contents].
Output. Return the fully expanded string after applying every repetition, including nested repetitions.
Rules. Repeat counts are positive ASCII integers immediately followed by balanced brackets.
Literal text contains no digits or bracket syntax. Adjacent pieces are concatenated in their original order.
Empty input returns "". Assume valid input; parsing malformed or untrusted text is a different task.
Example. "3[a2[c]]" returns "accaccacc".
The inner expression becomes "acc", which is then repeated three times.
For "2[a]bc", return "aabc".
Picture: Save the Entire Suspended Context
Problem trace
Separate nested input: save and restore the complete outer context
- top saved context
- (0, 0)
- input
- 3[a2[c]]
- layout
- outer to inner
- repeat
- 0→3
- action
- initialize→0 * 10 + 3
- repeat
- 3→0
- action
- 0 * 10 + 3→push and reset
- column 0 / row 0
- empty→("", 3)
- current
- ""→"a"
- action
- push and reset→append a
- repeat
- 0→2
- action
- append a→0 * 10 + 2
- top saved context
- (0, 0)→(1, 0)
- current
- "a"→""
- repeat
- 2→0
- current
- ""→"c"
- action
- push and reset→append c
- top saved context
- (1, 0)→(0, 0)
- current
- "c"→"acc"
- action
- append c→"a" + "c" * 2
- current
- "acc"→"accaccacc"
- action
- "a" + "c" * 2→"" + "acc" * 3
- result
- not shown→accaccacc
- 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.
Reference drawing
Problem trace
Finish the inner repetition before applying the outer count
Execution trace
- top saved context
- (0, 0)
- input
- 3[a2[c]]
- layout
- outer to inner
- repeat
- 0→3
- action
- initialize→0 * 10 + 3
- repeat
- 3→0
- action
- 0 * 10 + 3→push and reset
- column 0 / row 0
- empty→("", 3)
- current
- ""→"a"
- action
- push and reset→append a
- repeat
- 0→2
- action
- append a→0 * 10 + 2
- top saved context
- (0, 0)→(1, 0)
- current
- "a"→""
- repeat
- 2→0
- current
- ""→"c"
- action
- push and reset→append c
- top saved context
- (1, 0)→(0, 0)
- current
- "c"→"acc"
- action
- append c→"a" + "c" * 2
- current
- "acc"→"accaccacc"
- action
- "a" + "c" * 2→"" + "acc" * 3
- result
- not shown→accaccacc
- 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.
| Event | Saved stack, outer to inner | Active current |
|---|---|---|
Outer [ | ("", 3) | "" |
Read a, then inner [ | ("", 3), ("a", 2) | "" |
| Read c | Unchanged | "c" |
Inner ] | ("", 3) | "a" + "c" * 2 = "acc" |
Outer ] | Empty | "acc" * 3 = "accaccacc" |
At [, save (current, repeat) and reset both. Each frame holds exactly what one outer level needs when its child finishes.
At ], pop only that frame. Build decimal counts with repeat*10+digit; 12[a] needs twelve copies, not three.
Code
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
Time includes parsing plus all intermediate copied/materialized characters, not just final output length. Nested concatenations can copy a growing result repeatedly. Integer count arithmetic has additional bit costs. Storage includes output, suspended prefixes, counts and nesting frames.
Change 1: Compute Length Without Expansion
New task. Return decoded size, not text.
Picture and change. Replace every active and saved string with its length; keep the same nesting computation.
Code.
def decoded_length(text):
stack = []
current = repeat = 0
for character in text:
if "0" <= character <= "9":
repeat = repeat * 10 + int(character)
elif character == "[":
stack.append((current, repeat))
current = repeat = 0
elif character == "]":
previous, count = stack.pop()
current = previous + current * count
else:
current += 1
return current
Check. 3[a2[c]] gives 9; 1000000[a] gives 1,000,000 without creating that output.
Use when. Only size or a preflight limit is needed. Large-integer arithmetic still costs work.
Change 2: Cap Active Expansion Before Allocation
New task. Return None if an active expansion exceeds a nonnegative integer limit.
Picture and change. Check the resulting size before repetition/concatenation, and check literal growth.
Code.
def decode_bounded(text, limit):
stack = []
current = ""
repeat = 0
for character in text:
if "0" <= character <= "9":
repeat = repeat * 10 + int(character)
elif character == "[":
stack.append((current, repeat))
current, repeat = "", 0
elif character == "]":
previous, count = stack.pop()
if len(previous) + len(current) * count > limit:
return None
current = previous + current * count
else:
if len(current) + 1 > limit:
return None
current += character
return current
Check. Source input with cap 9 succeeds; 1000000[a] with cap 10 returns None before allocating the repeated string.
Use when. Valid input needs a size limit. This does not cap input length, nesting depth, total work or count arithmetic.
Failure: Saving Only the Count
The inner repeat must restore outer prefix "a" as well as count 2. Otherwise "acc" cannot be reconstructed correctly.
Transfer Check
Why cannot one global repeat counter handle nested brackets?
Reasoned Answer
Entering the inner repeat replaces active state. The outer count and prefix must remain suspended until that child finishes.
Distinguish Output Size From Total Copying
Start with a and wrap it repeatedly as a1[previous].
After levels, output has characters, but closing brackets concatenate lengths .
Those nonempty-prefix concatenations repeatedly copy growing strings: their total is quadratic in .
This is an operation-count argument, not a measured performance benchmark or a claim about every interpreter optimization.
A nested repeated group can also make final output exponential in encoded length. Length-only evaluation avoids materializing it, but still needs nesting state and large integers. With positive repeats, suspended prefixes contribute to eventual output; peak character/frame storage can be bounded by . Here is encoded length and is decoded length, with numeric bit costs accounted separately.
The original isdigit() plus int() is not a general Unicode numeric grammar.
Malformed brackets, misplaced counts, escapes and non-ASCII digit policies require validation outside the stated contract.
The bounded variant does not provide those checks or a complete memory/time budget for hostile input.
For that use, add grammar, depth, input-size and arithmetic limits before trusting expansion.