Expand a Compressed Bracket Pattern String
Stacks & QueuesAuto-graded · 21 test casesLast updated
Tests stack-based parsing of nested repeat-count patterns, including multi-digit counts, nesting, and trailing letters, to rebuild the fully expanded string.
Expand a Compressed Bracket Pattern String
A text has been compressed using a simple repetition notation: a positive integer k followed by a bracketed block [block] means the content of block should appear exactly k times in a row. Blocks may themselves contain further compressed segments, so the notation can be nested to any depth.
Write a function that takes the compressed text and returns the fully expanded text.
Rules
- The compressed text contains lowercase or uppercase letters, digits, and the characters
[and]. - Digits only appear as a repetition count placed immediately before a
[. A count may have more than one digit (for example12[x]), and it is always a positive integer. - Letters outside any bracket are copied to the output unchanged, in their original position.
- Brackets are always balanced and properly nested.
- Expand inner blocks first; the expanded result then counts as ordinary content of the enclosing block.
- An empty input string produces an empty output string.
Input
s: the compressed string.
Output
- A string: the fully expanded text.
Constraints
0 <= len(s) <= 30is typical, though the approach should work for any well-formed input.- The input is always well formed (balanced brackets, counts always followed by
[), so no error handling is required. - Every repetition count is a positive integer.
- The expanded output fits comfortably in memory.
Examples
Example 1
Input: expand_pattern('3[a]2[bc]')
Output: 'aaabcbc'
Example 2
Input: expand_pattern('2[a3[b]]')
Output: 'abbbabbb'
Example 3
Input: expand_pattern('')
Output: ''
Hints
Hint 1
Expansion is recursive: a bracket can contain more brackets. Think about which data structure lets you simulate recursion in a single left-to-right scan.
Hint 2
Keep two pieces of state for the current nesting level: the characters built so far and the number you are currently reading. Build multi-digit numbers with count = count * 10 + digit.
Hint 3
On '[', save the outer text together with the pending count and start fresh. On ']', pop that pair and set the current text to the saved outer text plus the inner text repeated count times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because brackets can nest, the structure is recursive. A stack lets us handle this in one left-to-right pass.
We track two things for the nesting level we are currently in:
current: a list of characters decoded so far at this level.repeat: the count being read, built withrepeat = repeat * 10 + digitso multi-digit counts work.
For each character:
| Character | Action |
|---|---|
| digit | Update repeat. |
[ | Push (current, repeat) onto the stack, then start a fresh current and reset repeat to 0. |
] | Pop (previous, count), then append current repeated count times to previous, and make that the new current. |
| letter | Append it to current. |
When the scan finishes, current holds the fully expanded top level.
Why it is correct
Each [ opens a new scope. The pushed pair stores what was built before the scope and the count that applies to it. Since brackets close in last-in-first-out order, the matching ] always pops exactly the frame that was pushed by its own [, so the right count is paired with the right block. The innermost block is expanded first, and its result becomes ordinary content of its parent, which is exactly the required semantics. Letters after a ] are appended to the restored outer level, preserving order. An empty string never enters the loop and yields an empty result.
Complexity
Let n = len(s) and L be the length of the output.
- Time: O(n + L) in typical cases, since each character is scanned once and the repeated content is copied into the output. Extending the previous list in place keeps appends amortized linear.
- Space: O(L) for the output plus O(d) stack frames for nesting depth
d.
Reference solution
def expand_pattern(s: str) -> str:
stack = []
current = []
repeat = 0
for ch in s:
if ch.isdigit():
repeat = repeat * 10 + int(ch)
elif ch == '[':
stack.append((current, repeat))
current = []
repeat = 0
elif ch == ']':
previous, count = stack.pop()
previous.extend(current * count)
current = previous
else:
current.append(ch)
return ''.join(current)