Home
DSA Patterns
Stack
Decode String
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
Visualize how the stack builds nested strings from the inside out.
Dry Run
Input: 3[a2[c]]
| Char | Action | Stack |
|---|---|---|
3,[,a,2,[,c |
Push all | ['3', '[', 'a', '2', '[', 'c'] |
] |
Pop until [. K=2. Repeat c x2. |
['3', '[', 'a', 'cc'] |
] |
Pop until [. String=acc. K=3. Repeat acc x3. |
['accaccacc'] |
Result: accaccacc
Edge Cases & Common Mistakes
- Multi-digit K: e.g.,
10[a]. Ensure you parse the full number. - Empty Brackets:
3[]-> Empty string. - No Brackets:
abc->abc.
Solution
Stack Implementation.
Decode String Code
1var decodeString = function(s) {2 const stack = [];3 for (const ch of s) {4 if (ch !== ']') {5 stack.push(ch);6 } else {7 let chunk = '';8 while (stack[stack.length - 1] !== '[') {9 chunk = stack.pop() + chunk;10 }11 stack.pop(); // drop "["12 let k = '';13 while (stack.length > 0 && /^\d$/.test(stack[stack.length - 1])) {14 k = stack.pop() + k;15 }16 stack.push(chunk.repeat(Number(k)));17 }18 }19 return stack.join('');20};
