Decompress Braces

Decompress Braces

A string is compressed as <number>{<content>} groups, where the content is repeated number times. Groups can be nested — a group's content may itself contain another group, like a box inside a box (e.g. 2{a2{b}}, where the inner 2{b} sits inside the outer group). Decompress it.

decompressBraces(s)

Numbers are single or multi digit; content contains letters and nested groups.

Input format: the compressed string.

Examples

"2{q}"        // → "qq"
"2{a2{b}}"    // → "abbabb"
"3{ab}1{z}"   // → "abababz"

Walkthrough

Thinking it through

The hard part is nesting: 2{a2{b}} contains a complete group inside another. The inner group has to finish, repeat, and fold back into the outer group's in-progress content before the outer group closes. "Pause what you're building, build something smaller, resume where you left off" is a nested-scope signal — exactly what a stack manages.

Why you need to save state, not just process linearly

A single flat "current output" variable breaks the moment you hit a nested {: you'd need both "what was I building before this group" and "how many times does this group repeat," possibly several levels deep (3{a2{b2{c}}}). Each nesting level needs its own private count and its own private partial string, and closing a } must restore exactly the enclosing level's state.

Building the two-stack approach

Two parallel stacks — pending counts, pending partial strings — plus two "current" variables:

  1. Reading digits: accumulate into the current number (multiply by ten, add the digit, for multi-digit counts).
  2. Reading letters: append to the current string segment.
  3. On {: push the current count and string segment (freezing the outer context), reset both for the inner group.
  4. On }: pop the saved count and string. Repeat the finished inner content that many times, append onto the saved segment — that becomes the new current as you resume the outer level.
  5. At the end, the current segment is the fully decompressed answer.

Why this generalizes cleanly

Each { is "remember where I was, start fresh"; each } is "finish, restore where I was" — the push/pop rhythm of function calls, expression parsing, and any bracket-nested structure. Perfectly paired pushes and pops handle arbitrarily deep nesting automatically.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.