Decode String - Problem
Imagine you're working with a compressed text format where repeated patterns are encoded in a special way. Given an encoded string, your task is to decode it and return the original expanded string.
The encoding follows this simple rule: k[encoded_string], where the encoded_string inside the square brackets should be repeated exactly k times. The number k is guaranteed to be a positive integer.
Key Points:
- The input string is always valid with well-formed brackets
- No extra whitespaces exist
- Original data contains no digits (digits are only for repeat counts)
- Patterns can be nested:
2[a3[bc]]means repeata3[bc]twice - Output length will never exceed 105
Examples:
"3[a]"→"aaa""2[bc]"→"bcbc""3[a2[c]]"→"accaccacc"
Input & Output
example_1.py — Simple Repetition
$
Input:
s = "3[a]"
›
Output:
"aaa"
💡 Note:
The letter 'a' should be repeated 3 times, resulting in "aaa".
example_2.py — Nested Pattern
$
Input:
s = "2[bc]"
›
Output:
"bcbc"
💡 Note:
The string "bc" should be repeated 2 times, resulting in "bcbc".
example_3.py — Complex Nesting
$
Input:
s = "3[a2[c]]"
›
Output:
"accaccacc"
💡 Note:
First, "2[c]" becomes "cc". Then "3[acc]" becomes "accaccacc".
Visualization
Tap to expand
Understanding the Visualization
1
Identify Structure
Parse the string to identify nested bracket patterns, like layers of an onion
2
Handle Nesting
Use recursion or stack to manage the nested structure - process inner patterns first
3
Expand & Combine
Multiply inner results by their repeat counts and combine with outer context
4
Build Final Result
Continue until all patterns are expanded and merged into the final decoded string
Key Takeaway
🎯 Key Insight: The problem is essentially about parsing nested structures - use recursion or a stack to handle the nesting elegantly, processing from innermost to outermost patterns.
Time & Space Complexity
Time Complexity
O(n)
Each character is processed exactly once during the recursion
✓ Linear Growth
Space Complexity
O(d)
Recursion stack depth d where d is the maximum nesting level
✓ Linear Space
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]
- The length of the output will never exceed 105
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code