Expand Nested Repeat Patterns in an Encoded String
Stacks & QueuesAuto-graded · 16 test casesLast updated
Tests stack-based parsing of nested, multi-digit repeat patterns of the form count[text] to rebuild the fully expanded string.
Expand Nested Repeat Patterns in an Encoded String
A compact text format uses repeat markers to shorten strings. A marker looks like k[text], where k is a positive integer and text is whatever sits between the square brackets. The marker stands for text written out k times in a row. The text inside a marker may itself contain further markers, to any depth.
Given an encoded string s, return the fully expanded string.
Details
- The input is always well formed: brackets are balanced, and every
[is immediately preceded by its repeat count. - Counts can have more than one digit (for example
12[x]). - Letters may appear outside any brackets, before, between, or after markers, and they are copied as-is.
- Digits only appear as repeat counts; they are never part of the text to be repeated.
- An empty input string expands to an empty string.
Constraints
sconsists of lowercase and uppercase English letters, digits,[and].- Every repeat count
kis a positive integer. - The expanded result fits comfortably in memory.
- The input is guaranteed to be valid, so no error handling is needed.
Examples
Example 1
Input: expand_encoded('3[a]2[bc]')
Output: 'aaabcbc'
Hints
Hint 1
Nested markers mean you must pause the text you are building, handle the inner marker, then resume. Which data structure naturally supports pausing and resuming?
Hint 2
Keep two running values while scanning left to right: the repeat count being read (digits accumulate as count * 10 + digit) and the text built so far at the current nesting level.
Hint 3
On `[`, save the text built so far together with the pending count on the stack and start fresh. On `]`, pop that pair and set the current text to the saved text plus the current text repeated count times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Nested markers require pausing the text being built, expanding an inner marker, and then resuming. A stack models this directly.
Scan the string left to right while maintaining:
number: the repeat count currently being read. Each new digit updates it asnumber * 10 + digit, so multi-digit counts work.current: a list of characters holding the expanded text at the current nesting level.
For each character:
- Digit: extend
number. [: push the pair(current, number)onto the stack, then start a new emptycurrentand resetnumberto 0.]: pop(previous, repeat)and setcurrent = previous + current * repeat.- Letter: append it to
current.
At the end, join current into a string.
Why it is correct
The invariant is that current always holds the fully expanded text of the innermost open bracket (or of the top level when none is open). Each stack entry stores the enclosing level's text and the multiplier for the bracket that interrupted it. When ] arrives, the inner segment is complete, so repeating it and appending it to the saved text restores the invariant one level up. Since the input is valid, the stack is empty at the end and current is the answer.
Complexity
- Time: proportional to the output size, times at most the nesting depth because of list copying at each
]. - Space: O(output size) for the result, plus O(depth) for the stack.
Reference solution
def expand_encoded(s: str) -> str:
stack = []
number = 0
current = []
for char in s:
if char.isdigit():
number = number * 10 + int(char)
elif char == '[':
stack.append((current, number))
current = []
number = 0
elif char == ']':
previous, repeat = stack.pop()
current = previous + current * repeat
else:
current.append(char)
return ''.join(current)