Banner Expander

Medium · Stack & Monotonic Stack · about 25 min

A shop's scrolling sign stores its text in a short form: k[text] means text written k times in a row. Groups can be nested, and k is a positive integer that may have more than one digit. Letters are lowercase and never appear as digits; brackets are always balanced, and every [ comes right after its count.

Return the fully expanded text.

Example: banner_expander("3[ab]2[c]") → "abababcc"

Example: banner_expander("2[a3[b]]") → "abbbabbb"

Constraints: the short form has 0 to 100 characters; the expanded text has at most 100,000 characters.

Hints

  • When a group opens, you are in the middle of building some text. What must you remember so you can continue it after the group closes?
  • Push the text built so far and the repeat count when you see an opening bracket, then start with empty text.
  • On a closing bracket, pop: new text = paused text + current text repeated count times. Read counts digit by digit.

Learn the pattern first: the Stack & Monotonic Stack lesson.

More Stack & Monotonic Stack problems