You are given an encoded string that uses the format k[content], where the bracketed content is repeated exactly k times. Encodings can be nested, so a bracketed section may itself contain more k[content] pieces. Return the fully expanded, decoded string.
The input is always well formed: brackets are balanced, repeat counts are positive integers, and letters outside brackets simply appear as themselves. There are no stray digits that are not tied to a bracketed block.
Example 1
Input: s = "2[ab]3[c]"
Output: "ababccc"
"ab" repeats twice and "c" repeats three times, concatenated in order.
Example 2
Input: s = "2[a2[b]]"
Output: "abbabb"
The inner "2[b]" becomes "bb", giving "abb", and the outer count doubles that to "abbabb".
Constraints
1 ≤ s.length ≤ 30s consists of lowercase English letters, digits, and square brackets1 ≤ k ≤ 300 for every repeat countThe input is guaranteed to be a valid encodingSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI