AlgoInsight

DSA problem

Decode String

MediumRecursionPattern: Recursiontop150AmazonGoogleMicrosoftAppleBloombergMeta

Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. You may assume the input is always valid; for example, there are no extra white spaces, the square brackets are well-formed, and the digits are only used for the repeat numbers.

The grammar is small but recursive: a decoded string is a sequence of literal characters and k[…] blocks, and the body of every k[…] block is itself a decoded string. That recursive structure is exactly what makes a recursive (or stack-based) parser the natural fit. Naive string repetition still gives the correct answer, but writing it cleanly requires either explicit stacks or recursion.

The optimal recursive approach scans the input with a shared cursor. While the character is a digit, accumulate it into the current repeat count k. When you hit [, advance past it and recurse to decode the inner string; the recursion stops when it sees ]. After the recursion returns, append the inner result k times to the current buffer. Any plain letter is appended directly.

Because the recursion only descends when a [ is encountered and unwinds on the matching ], bracket pairing is handled implicitly by the call stack. Each character of the output is produced exactly once, giving O(N * maxK) time, where N is the input length and maxK is the largest repeat count. The auxiliary space is O(d) recursion depth plus O(N * maxK) for the output buffer.

Examples

Example 1
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Explanation: The first block `3[a]` decodes to "aaa" and the second block `2[bc]` decodes to "bcbc". Concatenating yields "aaabcbc".
Example 2
Input: s = "3[a2[c]]"
Output: "accaccacc"
Explanation: The inner block `2[c]` decodes to "cc"; the outer becomes `3[acc]` which is "accaccacc". Nested brackets are resolved by the recursive structure.
Example 3
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
Explanation: `2[abc]` → "abcabc", `3[cd]` → "cdcdcd", and the trailing literal "ef" is appended unchanged.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

recursionstringstackparsing

Browse all DSA problems