KatInterview

Decode a Run-Length Encoded String With Nested Groups

StringsAuto-graded · 17 test cases
MediumAuto-gradedStringsstringsparsingstack

Last 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 abc represents itself.
  • A repeat group has the form N[content], where N is a positive integer (no leading zeros, always ≥ 1) and content is any valid encoded string (which may itself contain further repeat groups). The group expands to content repeated N times.
  • 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 000 characters in the encoded form.
  • The decoded string may be much longer than the encoded string.
  • N in any repeat group satisfies 1 ≤ 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.