Decode a Run-Length Encoded String With Nested Groups
StringsAuto-graded · 17 test casesLast updated
Tests the ability to parse and expand a run-length encoded string that contains arbitrarily nested bracket groups, combining stack-based parsing with string manipulation.
Decode a Run-Length Encoded String With Nested Groups
You are given an encoded string built with the following rules:
- A bare letter sequence like
abcrepresents itself. - A repeat group has the form
N[content], whereNis a positive integer (no leading zeros, always ≥ 1) andcontentis any valid encoded string (which may itself contain further repeat groups). The group expands tocontentrepeatedNtimes. - Groups may be nested to any depth.
- The encoded string contains only lowercase English letters, digits,
[, and]. - There are no spaces or other characters.
Return the fully decoded (expanded) string.
Constraints
0 ≤ len(encoded) ≤ 2 000characters in the encoded form.- The decoded string may be much longer than the encoded string.
Nin any repeat group satisfies1 ≤ N ≤ 100.- The encoding is always valid (balanced brackets, every
[is preceded by a positive integer). - An empty string input returns an empty string.
Examples
Example 1
Input: decode_rle_string('3[ab]')
Output: 'ababab'
Example 2
Input: decode_rle_string('2[a3[b]]')
Output: 'abbbabbb'
Example 3
Input: decode_rle_string('hello')
Output: 'hello'
Hints
Hint 1
Think about what information you need to save when you open a `[` — you need to remember the string built so far and the repeat count you are about to apply.
Hint 2
A stack works naturally here: push (current_string, repeat_count) onto the stack when you encounter `[`, and pop when you encounter `]` to finalize the repeated segment.
Hint 3
Parse multi-digit numbers carefully: scan all consecutive digit characters before the `[` to form the full integer multiplier.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
Run-length encoded strings with nested groups are a classic application of an explicit stack that mirrors the implicit call stack of a recursive decoder. Whenever we open a new group (N[), we save the string we have built so far and the repeat count; when we close it (]), we retrieve that saved state and append the current segment repeated the right number of times.
Algorithm (single linear scan)
- Maintain
current(the string being assembled at the current nesting depth) and astackof(saved_string, repeat_count)pairs. - Walk through
encodedcharacter by character:- Digit: collect all consecutive digits to form a (possibly multi-digit) integer
repeat, then skip the mandatory[. Push(current, repeat)onto the stack and resetcurrent = "". ]: pop(prev, repeat)from the stack; setcurrent = prev + current * repeat.- Letter: append it to
current.
- Digit: collect all consecutive digits to form a (possibly multi-digit) integer
- After the loop
currentholds the fully decoded string.
Why it is correct
Every N[…] group is fully resolved when its matching ] is encountered. Because we push state on [ and restore it on ], deeper nesting levels are always resolved before shallower ones, exactly mirroring the structure of the encoding grammar.
Edge cases handled
- Empty string — the loop body never executes;
current = ""is returned. - No groups — characters are appended directly; the stack is never used.
- Multi-digit multipliers (e.g.
10[x],100[a]) — the digit-collection loop accumulates all digits before converting. - Deeply nested groups — the stack grows to the nesting depth and unwinds correctly.
Complexity
| Time | O(D) where D is the length of the decoded string (each output character is written once) |
| Space | O(D + nesting depth) for the stack and the output string |
def decode_rle_string(encoded: str) -> str:
stack = [] # each entry: (string_built_before_this_group, repeat_count)
current = "" # string being built at the current nesting level
i = 0
while i < len(encoded):
ch = encoded[i]
if ch.isdigit():
# collect the full (possibly multi-digit) number
num_start = i
while i < len(encoded) and encoded[i].isdigit():
i += 1
repeat = int(encoded[num_start:i])
# next character must be '['; skip it and push state
i += 1 # skip '['
stack.append((current, repeat))
current = ""
elif ch == ']':
prev_string, repeat = stack.pop()
current = prev_string + current * repeat
i += 1
else:
current += ch
i += 1
return current