KatInterview

Expand Nested Repeat Notation into a Full String

Stacks & QueuesAuto-graded · 24 test cases
MediumAuto-gradedStacks & Queuesstackstring-parsingnested-structures

Last updated

Expand a string containing nested count[text] repeat groups into its full form, using a stack or recursion to parse multi-digit counts and nesting correctly.

Expand Nested Repeat Notation

A text-packing tool stores strings using a compact repeat notation. A group is written as k[text], where k is a positive integer and text is made up of lowercase letters and, possibly, further groups of the same form. The group stands for text written out k times in a row, after text itself has been fully expanded.

Write a function that takes a packed string and returns the fully expanded string.

Rules

  • Letters that are not inside any group are copied to the output as they are.
  • Groups can appear one after another and can be nested inside each other.
  • Counts can have more than one digit, for example 12[ab] repeats ab twelve times.
  • A count applies only to the bracket group that comes immediately after it.
  • A group with empty text, such as 3[], expands to nothing.
  • An empty input string expands to an empty string.
  • The output is the plain concatenation of all expanded pieces in left-to-right order, with no separators.

Input

  • packed: a string in the notation above.

Output

  • A string containing the fully expanded text.

Constraints

  • packed contains only digits, lowercase English letters, [ and ].
  • packed is guaranteed to be well formed, so brackets are balanced and every [ is preceded by its count.
  • Nesting depth is at most 10.
  • The expanded result has at most 10^5 characters.

Examples

Example 1

Input: expand_packed('3[a]2[bc]')

Output: 'aaabcbc'

Example 2

Input: expand_packed('3[a2[c]]')

Output: 'accaccacc'

Hints

Hint 1

Each `[` starts a new level of nesting and each `]` ends the most recent one. Which data structure naturally tracks 'the most recent open thing'?

Hint 2

When you reach a `[`, save what you have built so far at this level together with the count just read, then start a fresh buffer for the inside of the group.

Hint 3

Remember that counts can have several digits (build them as `num = num * 10 + digit`), and reset the count after using it at a `[` so it does not leak into later groups.