Expand Nested Repeat Notation in a Compressed String
Stacks & QueuesAuto-graded · 18 test casesLast updated
Parse a string with nested count-and-bracket repeat markers and expand it fully, testing recursive or stack-based parsing and careful handling of multi-digit counts.
Expand a Compressed String
A text has been compressed using a simple repeat notation. Your job is to reverse the compression and return the full text.
Notation
- A group written as
k[body]stands for the textbodywritten outktimes in a row, wherekis a positive integer (it may have more than one digit, e.g.12[a]). - Groups can be nested: the
bodyof a group may itself contain other groups. - Any character that is not part of a group's count or brackets is plain text and is copied to the output unchanged.
Task
Write a function that takes the compressed string s and returns the fully expanded string.
Additional rules
- A run of digits that is not immediately followed by
[is plain text and is kept as is (for example,"ab12"expands to"ab12"). - An empty body such as
"3[]"expands to the empty string. - An empty input expands to the empty string.
- Inputs are expected to be well formed, with balanced brackets.
Constraints
0 <= len(s) <= 1000sconsists of letters, digits,[and].- Every repeat count
kis a positive integer. - The length of the expanded result is small enough to fit comfortably in memory.
Examples
Example 1
Input: expand_repeats('3[a]2[bc]')
Output: 'aaabcbc'
Example 2
Input: expand_repeats('3[a2[c]]')
Output: 'accaccacc'
Example 3
Input: expand_repeats('2[ab3[c]]x')
Output: 'abcccabcccx'
Hints
Hint 1
Notice that the body inside brackets is itself a complete compressed string, so the problem has a self-similar structure.
Hint 2
Keep a stack (or use recursion) so that when you meet an opening bracket you can save the text built so far together with the pending count, then start fresh for the inside.
Hint 3
Read all consecutive digits to form the count, not just one. When you reach a closing bracket, combine the saved text with the inner text repeated count times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The notation forms a small nested grammar: a compressed string is a sequence of plain characters and groups, and each group's body is itself a compressed string. This suggests a recursive parser.
Define a helper parse(i) that decodes from index i until it reaches a closing ] or the end of the input. It returns the decoded text and the index where the caller should resume (just after the ] if one was consumed).
Inside the loop:
- Non-digit character: append it directly to the output pieces.
- Run of digits: consume the entire run so multi-digit counts work. If the next character is
[, convert the digits tok, callparseon the position after the bracket to get the decoded body, and append the body repeatedktimes. If there is no[, the digits are plain text and are appended unchanged.
When the loop stops at ], the function skips over it and returns, letting the caller continue right after the group.
Why it is correct
Each call handles exactly one nesting level. With no brackets, every character is copied, which is correct. If parse correctly decodes any body of nesting depth d, then for depth d + 1 each group is replaced by k copies of a correctly decoded body while everything else is copied literally, which matches the definition. The returned index guarantees that no input is skipped or read twice.
Complexity
Let n be the input length, L the output length and d the maximum nesting depth.
- Time: each input character is scanned once. Building repeated strings costs additional work proportional to the output, up to
O(n + L * d)in the worst case. - Space:
O(L)for the result and intermediate strings, plusO(d)for the recursion stack.
An iterative alternative uses a stack of (text_before, count) pairs: push on [, and on ] pop and set current = text_before + current * count.
Reference solution
def expand_repeats(s: str) -> str:
n = len(s)
def parse(i):
parts = []
while i < n and s[i] != ']':
if s[i].isdigit():
start = i
while i < n and s[i].isdigit():
i += 1
if i < n and s[i] == '[':
count = int(s[start:i])
inner, i = parse(i + 1)
parts.append(inner * count)
else:
parts.append(s[start:i])
else:
parts.append(s[i])
i += 1
if i < n and s[i] == ']':
i += 1
return ''.join(parts), i
result, _ = parse(0)
return result