Recursion · Hard
Decode nested repeats
Expand a well-formed expression of lowercase letters and positive repeat counts followed by brackets. Counts may have multiple digits. A number repeats the entire bracketed expression that follows it. Expand the innermost brackets first.
Worked example
'3[a2[c]]' → 'accaccacc'
- Expand 2[c] into cc. The outer expression then reads 3[acc].
- Repeat acc three times to get accaccacc.
Python solution
def solve(expression):
cursor = 0
def parse():
nonlocal cursor
parts = []
while cursor < len(expression) and expression[cursor] != "]":
if expression[cursor].isdigit():
start = cursor
while expression[cursor].isdigit():
cursor = cursor + 1
count = int(expression[start:cursor])
cursor = cursor + 1
inner = parse()
cursor = cursor + 1
parts.append(inner * count)
else:
parts.append(expression[cursor])
cursor = cursor + 1
return "".join(parts)
return parse()Each recursive call consumes exactly one bracketed region using a shared input cursor.
Time: O(n + total expanded size across calls) · Space: O(n + output)