Decode String - Problem

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. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k.

For example, there will not be input like 3a or 2[4].

The test cases are generated so that the length of the output will never exceed 10⁵.

Input & Output

Example 1 — Nested Brackets
$ Input: s = "3[a2[c]]"
Output: "accaccacc"
💡 Note: First decode inner pattern: 2[c] → "cc", then 3[acc] → "accaccacc"
Example 2 — Sequential Patterns
$ Input: s = "2[bc]3[cd]ef"
Output: "bcbccdcdcdef"
💡 Note: Decode 2[bc] → "bcbc", then 3[cd] → "cdcdcd", combine with "ef" → "bcbccdcdcdef"
Example 3 — Simple Pattern
$ Input: s = "abc3[cd]xyz"
Output: "abccdcdcdxyz"
💡 Note: Keep "abc", decode 3[cd] → "cdcdcd", append "xyz" → "abccdcdcdxyz"

Constraints

  • 1 ≤ s.length ≤ 30
  • s consists of lowercase English letters, digits, and square brackets '[]'
  • s is guaranteed to be a valid input
  • All the integers in s are in the range [1, 300]

Visualization

Tap to expand
Decode String: Transform "3[a2[c]]" → "accaccacc"Input3[a2[c]]2[c] → cc3[acc] → accaccaccOutputaccaccaccDecoding Process1. Inner: 2[c] expands to "cc"2. Outer: 3[acc] expands to "accaccacc"
Understanding the Visualization
1
Input
Encoded string with nested bracket patterns
2
Process
Decode from innermost brackets outward
3
Output
Fully expanded decoded string
Key Takeaway
🎯 Key Insight: Use a stack or recursion to handle nested patterns by processing from innermost brackets outward
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.5K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen