Stack
Medium
Decode String
Decode an encoded string with nested repetition rules.
10 min read
Solve on LeetCodeProblem Understanding
You are given an encoded string where k[encoded_string] means the encoded_string inside the brackets is repeated exactly k times. You may assume the input string is always valid.
Example:
- Input:
3[a]2[bc]-> Output:aaabcbc - Input:
3[a2[c]]-> Output:accaccacc(Nested!)
Algorithm Strategy
We use a Stack to handle the nested nature of the problem.
- Initialize an empty stack.
- Iterate through the string character by character.
- If the char is NOT
], push it to the stack. - If the char IS
], we must start decoding:- Pop characters until we find
[. This is thestring_to_repeat. - Pop the
[. - Pop numbers to form
k(the repetition count). - Repeat
string_to_repeatktimes and Push it back to the stack.
- Pop characters until we find
- Finally, join the stack to get the result.
Interactive Visualization
Step 1 / 1
Empty Stack
Top Index: -1Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
