Skip to content
Decoder

Decode String

Medium

Problem

A string is encoded with the rule k[text], which means text repeated `k` times. Encodings can be nested, like 3[a2[c]]. Return the decoded string.

Example 1

Input
s = "3[a]2[bc]"
Output
"aaabcbc"

Example 2

Input
s = "3[a2[c]]"
Output
"accaccacc"

Example 3

Input
s = "2[abc]3[cd]ef"
Output
"abcabccdcdcdef"

Constraints

  • 1 <= s.length <= 30
  • s contains lowercase letters, digits and square brackets.
  • s is always valid; digits only appear as repeat counts, and 1 <= k <= 300.
  • The decoded string is at most 10^5 characters long.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.