Decode String

35 min · decodeString()

A short instruction can unfold into a wall of text. The challenge is remembering which instruction owns which piece when those instructions nest.

You're given an encoded string s. An encoded group has the form k[encoded], where k is a positive integer and the text inside the brackets must be repeated k times. Groups may appear inside other groups. Lowercase letters outside brackets are copied as they are.

Decode the entire string and return the expanded result.

A few ground rules:

  • Every number is a repeat count followed immediately by [.
  • Brackets are balanced, and every encoded group is complete.
  • Repeat counts apply only to the group directly after them.
  • The result always fits within the output limit below.

Constraints

  • 1 <= s.length <= 3_000
  • s contains only lowercase English letters, digits, [ and ].
  • Every number forms a repeat count k with 1 <= k <= 300.
  • Brackets are balanced, and the nesting depth is at most 10.
  • The decoded output length is at most 100_000.

Hints

Finish the innermost group first

A closing bracket tells you one complete piece is ready. Expand that piece before attaching it to the text that came before its opening bracket.

Follow the grammar

When a parser reaches [, it can decode the inner section by calling the same logic again. The matching ] returns that completed section to its caller.

Save two kinds of context

When [ arrives, save both the repeat count and the partial text built so far. Two stacks — one for counts and one for prefixes — let you restore both at ].

Follow-up

Could you calculate the decoded length without constructing the decoded string itself?

Visible cases

Examples

Example 1

ready
Input
s = "3[a]2[bc]"
Expected
"aaabcbc"
Why
repeat 'a' three times, then 'bc' twice

Example 2

ready
Input
s = "3[a2[c]]"
Expected
"accaccacc"
Why
decode the inner c-group before repeating the outer group

Example 3

ready
Input
s = "2[abc]3[cd]ef"
Expected
"abcabccdcdcdef"
Why
adjacent groups expand independently; trailing letters stay

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite