KatInterview

Expand a Compact Pattern with Nested Multipliers

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

Last updated

Expand a string in which a positive integer followed by a bracketed block means that block repeats, with nesting; tests stack or recursive parsing and multi-digit number handling.

Expand a Compact Pattern

You are given a compressed text pattern. It is written using a simple repetition notation: a positive integer k immediately followed by a bracketed block [block] means that block is written out k times in a row, one copy right after another.

Blocks may themselves contain further repetition groups, so notation can be nested to any depth. For example, 3[a2[c]] expands to accaccacc.

Return the fully expanded text.

Rules

  • The input is always well formed: brackets are balanced, and every number is directly followed by [.
  • Every repetition count is a positive integer and may have more than one digit. For instance, 12[a] is the letter a repeated 12 times.
  • Letters outside any brackets are copied to the output unchanged and in their original order.
  • A pattern with no brackets at all is returned as is.
  • Only the characters described in the constraints appear in the input; digits only ever appear as repetition counts, never as literal output characters.

Function

Implement expand_pattern(pattern), which takes the compressed string and returns the expanded string.

Constraints

  • 1 <= len(pattern) <= 30
  • pattern consists only of lowercase English letters, digits, [ and ].
  • The expanded result has length at most 10^5.

Examples

Example 1

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

Output: 'aaabcbc'

Example 2

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

Output: 'accaccacc'

Example 3

Input: expand_pattern('2[abc]3[cd]ef')

Output: 'abcabccdcdcdef'

Hints

Hint 1

Each `[` starts a new inner context and each `]` finishes the most recent one, so the most recently opened group is always the first one to close. Which data structure matches that?

Hint 2

Read the number digit by digit using `count = count * 10 + digit` so multi-digit counts like `12` work correctly.

Hint 3

When you hit `[`, save the text built so far together with the pending count, then start a fresh empty text. When you hit `]`, pop the saved entry and append the inner text repeated that many times to the saved text.