FAANGPrep Sprint
Decode String
Decode an encoded string with nested repetition rules.
MediumSolve on LeetCode
Problem 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
"3[a2[c]]"
READ
encoded
i
3
0
[
1
a
2
2
3
[
4
c
5
]
6
]
7
stack
empty
chunk
—
k
—
Result
—
Read '3' at 0
Next
'3' is not ']': push it
Encoded
Visualize how the stack builds nested strings from the inside out.
