KatInterview

Expand a Compressed Bracket Pattern String

Stacks & QueuesAuto-graded · 21 test cases
MediumAuto-gradedStacks & Queuesstackstringparsing

Last updated

Tests stack-based parsing of nested repeat-count patterns, including multi-digit counts, nesting, and trailing letters, to rebuild the fully expanded string.

Expand a Compressed Bracket Pattern String

A text has been compressed using a simple repetition notation: a positive integer k followed by a bracketed block [block] means the content of block should appear exactly k times in a row. Blocks may themselves contain further compressed segments, so the notation can be nested to any depth.

Write a function that takes the compressed text and returns the fully expanded text.

Rules

  • The compressed text contains lowercase or uppercase letters, digits, and the characters [ and ].
  • Digits only appear as a repetition count placed immediately before a [. A count may have more than one digit (for example 12[x]), and it is always a positive integer.
  • Letters outside any bracket are copied to the output unchanged, in their original position.
  • Brackets are always balanced and properly nested.
  • Expand inner blocks first; the expanded result then counts as ordinary content of the enclosing block.
  • An empty input string produces an empty output string.

Input

  • s: the compressed string.

Output

  • A string: the fully expanded text.

Constraints

  • 0 <= len(s) <= 30 is typical, though the approach should work for any well-formed input.
  • The input is always well formed (balanced brackets, counts always followed by [), so no error handling is required.
  • Every repetition count is a positive integer.
  • The expanded output fits comfortably in memory.

Examples

Example 1

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

Output: 'aaabcbc'

Example 2

Input: expand_pattern('2[a3[b]]')

Output: 'abbbabbb'

Example 3

Input: expand_pattern('')

Output: ''

Hints

Hint 1

Expansion is recursive: a bracket can contain more brackets. Think about which data structure lets you simulate recursion in a single left-to-right scan.

Hint 2

Keep two pieces of state for the current nesting level: the characters built so far and the number you are currently reading. Build multi-digit numbers with count = count * 10 + digit.

Hint 3

On '[', save the outer text together with the pending count and start fresh. On ']', pop that pair and set the current text to the saved outer text plus the inner text repeated count times.