Skip to content
mlmentorship

Decode String

Decode text such as `3[a2[c]]` into `accaccacc`.

Published · 12 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Decode String

Explain the mechanism, why it works, when it fails, and one alternative.

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".

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Each [ saves its outer string and repeat count so ] can restore exactly one nesting level.

Problem trace

Finish the inner repetition before applying the outer count

Worked example: finish the inner repeat before applying its outer multiplierFor 2[a3[b]], first decode 3[b] to bbb. Then repeat the completed abbb twice.Resolve the inner repeat beforecopying the completed outer payloadOuter repeat: two whole payloadsaInner: three b copiesbbbCompleted inner payload: abbbRepeat that whole completed payloadtwiceabbbabbb
Read it this way: For 2[a3[b]], first decode 3[b] to bbb. Then repeat the completed abbb twice. Would repeating the outer a before resolving its inner b group produce the same payload?
Full interview answer 12 min read
Reading depth

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

Input and goalDecode text such as `3[a2[c]]` into `accaccacc`.
Initialize decoder stateBefore scanning 3[a2[c]], stack=[], current="", and repeat=0.
emptytop saved context
input3[a2[c]]layoutouter to innercurrent""repeat0actioninitialize
top saved context
(0, 0)
input
3[a2[c]]
layout
outer to inner

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.
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.
Check: Why does closing the inner bracket produce acc before the outer count 3 is applied?
Reference drawing

Problem trace

Finish the inner repetition before applying the outer count

Worked example: finish the inner repeat before applying its outer multiplierFor 2[a3[b]], first decode 3[b] to bbb. Then repeat the completed abbb twice.Resolve the inner repeat beforecopying the completed outer payloadOuter repeat: two whole payloadsaInner: three b copiesbbbCompleted inner payload: abbbRepeat that whole completed payloadtwiceabbbabbb
Execution trace
Input and goalDecode text such as `3[a2[c]]` into `accaccacc`.
Initialize decoder stateBefore scanning 3[a2[c]], stack=[], current="", and repeat=0.
emptytop saved context
input3[a2[c]]layoutouter to innercurrent""repeat0actioninitialize
top saved context
(0, 0)
input
3[a2[c]]
layout
outer to inner

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.
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.
Check: Why does closing the inner bracket produce acc before the outer count 3 is applied?
Read it this way: For 2[a3[b]], first decode 3[b] to bbb. Then repeat the completed abbb twice. Would repeating the outer a before resolving its inner b group produce the same payload?
EventSaved stack, outer to innerActive current
Outer [("", 3)""
Read a, then inner [("", 3), ("a", 2)""
Read cUnchanged"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.