KatInterview

Expand Nested Repeat Patterns in an Encoded String

Stacks & QueuesAuto-graded · 16 test cases
MediumAuto-gradedStacks & Queuesstackstring-parsingnested-structure

Last updated

Tests stack-based parsing of nested, multi-digit repeat patterns of the form count[text] to rebuild the fully expanded string.

Expand Nested Repeat Patterns in an Encoded String

A compact text format uses repeat markers to shorten strings. A marker looks like k[text], where k is a positive integer and text is whatever sits between the square brackets. The marker stands for text written out k times in a row. The text inside a marker may itself contain further markers, to any depth.

Given an encoded string s, return the fully expanded string.

Details

  • The input is always well formed: brackets are balanced, and every [ is immediately preceded by its repeat count.
  • Counts can have more than one digit (for example 12[x]).
  • Letters may appear outside any brackets, before, between, or after markers, and they are copied as-is.
  • Digits only appear as repeat counts; they are never part of the text to be repeated.
  • An empty input string expands to an empty string.

Constraints

  • s consists of lowercase and uppercase English letters, digits, [ and ].
  • Every repeat count k is a positive integer.
  • The expanded result fits comfortably in memory.
  • The input is guaranteed to be valid, so no error handling is needed.

Examples

Example 1

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

Output: 'aaabcbc'

Hints

Hint 1

Nested markers mean you must pause the text you are building, handle the inner marker, then resume. Which data structure naturally supports pausing and resuming?

Hint 2

Keep two running values while scanning left to right: the repeat count being read (digits accumulate as count * 10 + digit) and the text built so far at the current nesting level.

Hint 3

On `[`, save the text built so far together with the pending count on the stack and start fresh. On `]`, pop that pair and set the current text to the saved text plus the current text repeated count times.