KatInterview

Expand Nested Repeat Notation in a Compressed String

Stacks & QueuesAuto-graded · 18 test cases
MediumAuto-gradedStacks & Queuesstringsstackrecursion

Last 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 text body written out k times in a row, where k is a positive integer (it may have more than one digit, e.g. 12[a]).
  • Groups can be nested: the body of 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) <= 1000
  • s consists of letters, digits, [ and ].
  • Every repeat count k is 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.