Unpack a Nested String

MediumStack≈ 35 min

A string is packed by writing k[text] for text repeated k times: 3[ab] stands for "ababab". Packed pieces can sit side by side and inside one another: 2[a3[b]] stands for "abbbabbb". Letters outside any brackets stand for themselves.

Given a packed string packed, return the string it stands for.

Examples

text
packed = "3[a]2[bc]"       →  "aaabcbc"
packed = "3[a2[c]]"        →  "accaccacc"
packed = "2[abc]3[cd]ef"   →  "abcabccdcdcdef"
packed = "xyz"             →  "xyz"

Constraints

  • Between 0 and 20,000 characters: lowercase letters, digits and brackets. The packed string is always well formed: every [ follows a count between 1 and 99 and is closed by a ], and digits appear only as counts.
  • The unpacked string is at most 100,000 characters long.
  • Aim for one pass over the packed string: O(n + d × m), n the packed length, m the unpacked one and d the deepest nesting.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.