Decode String
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
Decode String
Decode an encoded string where
k[encoded_string] means encoded_string is repeated k times.Visual Representation
s = "3[a]2[bc]"
1. '3': k = 3
2. '[': Push 3, Push "". Stack: [(3, "")]
3. 'a': curr = "a"
4. ']': Pop 3. res = "" + "a"*3 = "aaa"
5. '2': k = 2
6. '[': Push 2, Push "aaa". Stack: [(2, "aaa")]
7. "bc": curr = "bc"
8. ']': Pop 2. res = "aaa" + "bc"*2 = "aaabcbc"Examples
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Approach 1
Level I: Brute Force (Innermost Bracket First)
Intuition
Find the innermost
[] bracket pair using regex or string searching, expand it (repeat the inner string by the preceding number), replace it in the original string, and repeat until no brackets remain. This naturally handles nested brackets by working from inside out.⏱ O(N * maxK) — each pass expands one bracket group, and there can be N/2 groups.💾 O(N * maxK) for the expanded string.
Approach 2
Level III: Optimal (Two Stacks)
Intuition
Use two stacks: one to store the multipliers (
countStack) and one to store the strings built so far (resStack). When an opening bracket [ is met, push the current count and current string. When a closing bracket ] is met, pop the multiplier and the previous string, then append the repeated current string to the previous one.⏱ O(N * maxK)💾 O(N)
Detailed Dry Run
| Char | countStack | resStack | currStr |
|---|---|---|---|
| '3' | [] | [] | "" (k=3) |
| '[' | [3] | [""] | "" |
| 'a' | [3] | [""] | "a" |
| ']' | [] | [] | "aaa" |
⚠️ Common Pitfalls & Tips
Multi-digit numbers (like
100[a]) must be handled. Nested brackets are naturally handled by the stack.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.