Expand a Compact Pattern with Nested Multipliers
Stacks & QueuesAuto-graded · 23 test casesLast updated
Expand a string in which a positive integer followed by a bracketed block means that block repeats, with nesting; tests stack or recursive parsing and multi-digit number handling.
Expand a Compact Pattern
You are given a compressed text pattern. It is written using a simple repetition notation: a positive integer k immediately followed by a bracketed block [block] means that block is written out k times in a row, one copy right after another.
Blocks may themselves contain further repetition groups, so notation can be nested to any depth. For example, 3[a2[c]] expands to accaccacc.
Return the fully expanded text.
Rules
- The input is always well formed: brackets are balanced, and every number is directly followed by
[. - Every repetition count is a positive integer and may have more than one digit. For instance,
12[a]is the letterarepeated 12 times. - Letters outside any brackets are copied to the output unchanged and in their original order.
- A pattern with no brackets at all is returned as is.
- Only the characters described in the constraints appear in the input; digits only ever appear as repetition counts, never as literal output characters.
Function
Implement expand_pattern(pattern), which takes the compressed string and returns the expanded string.
Constraints
1 <= len(pattern) <= 30patternconsists only of lowercase English letters, digits,[and].- The expanded result has length at most
10^5.
Examples
Example 1
Input: expand_pattern('3[a]2[bc]')
Output: 'aaabcbc'
Example 2
Input: expand_pattern('3[a2[c]]')
Output: 'accaccacc'
Example 3
Input: expand_pattern('2[abc]3[cd]ef')
Output: 'abcabccdcdcdef'
Hints
Hint 1
Each `[` starts a new inner context and each `]` finishes the most recent one, so the most recently opened group is always the first one to close. Which data structure matches that?
Hint 2
Read the number digit by digit using `count = count * 10 + digit` so multi-digit counts like `12` work correctly.
Hint 3
When you hit `[`, save the text built so far together with the pending count, then start a fresh empty text. When you hit `]`, pop the saved entry and append the inner text repeated that many times to the saved text.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The notation is nested: every [ opens a new context and every ] closes the most recent one. That last-in, first-out behavior is exactly what a stack provides.
Scan the string once from left to right, keeping:
current: the characters decoded so far in the innermost open group (or at top level if none is open).count: the number currently being read. Since it can have several digits, update it withcount = count * 10 + digit.stack: saved states of the enclosing groups.
Actions per character:
- Digit: extend
count. [: push(current, count)onto the stack, then start a new emptycurrentand resetcountto 0.]: pop(previous, repeat)and setcurrent = previous + current * repeat.- Letter: append it to
current.
At the end the stack is empty and current is the answer.
Why it is correct
Invariant: current always holds the fully decoded content of the innermost unclosed group. Each stack entry holds the decoded text that preceded an open group in its parent, plus that group's multiplier.
- At
[, the parent's progress is saved and a new empty context starts, so the invariant holds. - At
], all groups nested inside the current one have already been closed and folded in, socurrentis completely decoded. Repeating itrepeattimes and attaching it after the saved prefix gives the parent's decoded content so far. - Because the input is valid, each
]has a matching stack entry and each number is followed by[, socountis always consumed and reset properly.
Edge cases: with no brackets, letters simply accumulate; multi-digit counts are handled by the digit accumulation; letters after a group go to the enclosing context; letters before a nested group were saved as the prefix.
Complexity
Let n be the input length and L the expanded length.
- Time: each closing bracket builds a list of size at most
L, so the worst case is O(n * L), though in practice it is close to O(L) and trivial under these limits. - Space: O(L + n) for the output and the stack.
Reference solution
def expand_pattern(pattern: str) -> str:
stack = [] # (text built before the group, repeat count of the group)
current = [] # characters of the innermost open context
count = 0 # number being parsed, may span several digits
for ch in pattern:
if ch.isdigit():
count = count * 10 + int(ch)
elif ch == '[':
stack.append((current, count))
current = []
count = 0
elif ch == ']':
previous, repeat = stack.pop()
current = previous + current * repeat
else:
current.append(ch)
return ''.join(current)