iq.lab
Python starts when a code cell comes near or you run one
mediumStack target 25 min

Decode string

A string is compressed with one rule: k[text] stands for text written k times in a row. So 3[ab] means ababab. Pieces can sit side by side (2[a]3[b] is aabbb) and can nest (2[a2[b]] is abbabb). Letters outside any brackets stay as they are.

Given a compressed string s, return the decoded string.

The input is always well formed: every [ comes right after its count k and has a matching ]. A count is a whole number, at least 1, and can have more than one digit. Digits appear only in counts, never in the text.

Example 1
Inputs = "2[ab]c"Output"ababc"

ab twice, then c.

Example 2
Inputs = "2[x3[y]]"Output"xyyyxyyy"

The inner 3[y] is yyy, so the outer bracket holds xyyy, written twice.

Example 3
Inputs = "x10[y]z"Output"xyyyyyyyyyyz"

A count can have several digits: 10[y] is ten copies of y, between the x and the z.

Constraints
  • 1 ≤ len(s) ≤ 106

  • 1 ≤ k ≤ 300

  • Brackets nest at most 500 deep.

  • The decoded string has at most 106 characters.

  • Every letter is a lowercase English letter.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.