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 - Optimal Solution INPUT s = "3[a2[c]]" 3 [ a 2 [ c ] ] Stack Structure Used: countStack | stringStack Count [3] [2] String [""] ["a"] Nested encoding pattern k[encoded_string] k = repeat count ALGORITHM STEPS 1 Initialize Stacks countStack, stringStack currentStr = "", num = 0 2 Process Each Char digit: num = num*10 + d letter: currentStr += c 3 On '[' Push Push num to countStack Push currentStr to strStack Reset: num=0, currentStr="" 4 On ']' Pop and Repeat k = pop countStack prev = pop stringStack currentStr = prev + k*cur Trace: "3[a2[c]]" '2[c]' --> 'c' * 2 = 'cc' 'a' + 'cc' = 'acc' '3[acc]' --> 'acc' * 3 = 'accaccacc' FINAL RESULT Decoded String: "accaccacc" Pattern Breakdown: acc acc acc "acc" repeated 3 times Inner Expansion: a + c c = acc 'c' x 2 = 'cc' 'a' + 'cc' = 'acc' Time: O(n) | Space: O(n) Key Insight: Use two stacks to handle nested brackets: one for repeat counts and one for accumulated strings. When encountering '[', push current state. When encountering ']', pop and repeat the inner string k times. This stack-based approach naturally handles nested patterns like "3[a2[c]]" by processing inside-out. TutorialsPoint - Decode String | Stack-Based Optimal Solution
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