Expand Nested Repeat Notation into a Full String
Stacks & QueuesAuto-graded · 24 test casesLast updated
Expand a string containing nested count[text] repeat groups into its full form, using a stack or recursion to parse multi-digit counts and nesting correctly.
Expand Nested Repeat Notation
A text-packing tool stores strings using a compact repeat notation. A group is written as k[text], where k is a positive integer and text is made up of lowercase letters and, possibly, further groups of the same form. The group stands for text written out k times in a row, after text itself has been fully expanded.
Write a function that takes a packed string and returns the fully expanded string.
Rules
- Letters that are not inside any group are copied to the output as they are.
- Groups can appear one after another and can be nested inside each other.
- Counts can have more than one digit, for example
12[ab]repeatsabtwelve times. - A count applies only to the bracket group that comes immediately after it.
- A group with empty text, such as
3[], expands to nothing. - An empty input string expands to an empty string.
- The output is the plain concatenation of all expanded pieces in left-to-right order, with no separators.
Input
packed: a string in the notation above.
Output
- A string containing the fully expanded text.
Constraints
packedcontains only digits, lowercase English letters,[and].packedis guaranteed to be well formed, so brackets are balanced and every[is preceded by its count.- Nesting depth is at most 10.
- The expanded result has at most 10^5 characters.
Examples
Example 1
Input: expand_packed('3[a]2[bc]')
Output: 'aaabcbc'
Example 2
Input: expand_packed('3[a2[c]]')
Output: 'accaccacc'
Hints
Hint 1
Each `[` starts a new level of nesting and each `]` ends the most recent one. Which data structure naturally tracks 'the most recent open thing'?
Hint 2
When you reach a `[`, save what you have built so far at this level together with the count just read, then start a fresh buffer for the inside of the group.
Hint 3
Remember that counts can have several digits (build them as `num = num * 10 + digit`), and reset the count after using it at a `[` so it does not leak into later groups.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The notation is recursive, so a stack is a natural fit: every [ opens a nesting level and every ] closes the most recent one.
Scan the string once from left to right, keeping three pieces of state:
current: a list of characters already decoded at the current nesting level.number: the count being read, which may have several digits.stack: one saved frame(outer_buffer, count)for each currently open bracket.
How each character is handled:
- Digit: update
number = number * 10 + digit. [: push(current, number)onto the stack, then start a new emptycurrentand resetnumberto 0.]: pop(previous, count). The finished group expands tocurrentrepeatedcounttimes, so append that topreviousand makepreviousthe newcurrent.- Letter: append it to
current.
At the end the stack is empty and current holds the expanded top-level string.
Why it works
Invariant: at any moment, current is the expanded content, read so far, of the innermost open group (or of the whole string if no group is open). The stack holds, for each enclosing level, the content that came before the open group and the group's multiplier.
- A letter extends the innermost content, so the invariant holds.
- A
[begins a new group with empty content. The enclosing content and the count are saved, so nothing is lost. - A
]finishes the innermost group, whose full expansion iscurrent * count. Appending it to the saved outer content gives exactly the enclosing level's content so far.
Resetting number at [ ensures a count is only used for the group it directly precedes.
Complexity
Let n be the input length, L the output length and D the nesting depth.
- Time: O(n + D * L). Each output character is copied at most once per enclosing level, and the extend-in-place step avoids re-copying the outer prefix.
- Space: O(n + L) for the stack frames and buffers.
Reference solution
def expand_packed(packed):
stack = []
current = []
number = 0
for ch in packed:
if ch.isdigit():
number = number * 10 + int(ch)
elif ch == '[':
stack.append((current, number))
current = []
number = 0
elif ch == ']':
previous, count = stack.pop()
previous.extend(current * count)
current = previous
else:
current.append(ch)
return ''.join(current)