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.
"2{q}" // → "qq"
"2{a2{b}}" // → "abbabb"
"3{ab}1{z}" // → "abababz"
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.
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.
Two parallel stacks — pending counts, pending partial strings — plus two "current" variables:
{: push the current count and string segment (freezing the outer context), reset both for the inner group.}: 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.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.
def decompress_braces(s):
num_stack = []
str_stack = []
cur = ""
num = 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == "{":
num_stack.append(num)
str_stack.append(cur)
num = 0
cur = ""
elif ch == "}":
k = num_stack.pop()
prev = str_stack.pop()
cur = prev + cur * k
else:
cur += ch
return cur
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.