Home
DSA Patterns
Stack
Decode String
Decode String (LeetCode 394)
Decode String (LeetCode 394): decode an encoded string with nested repetition rules.
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
0
1
2
3
4
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.
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};
Decode String in Python, Java, C++, TypeScript and C
Decode String in Python
class Solution:
def decodeString(self, s: str) -> str:
stack = []
for ch in s:
if ch != "]":
stack.append(ch)
else:
chunk = ""
while stack[-1] != "[":
chunk = stack.pop() + chunk
stack.pop() # drop "["
k = ""
while stack and stack[-1].isdigit():
k = stack.pop() + k
stack.append(chunk * int(k))
return "".join(stack)Decode String in Java
class Solution {
public String decodeString(String s) {
Deque<String> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c != ']') {
stack.push(String.valueOf(c));
} else {
StringBuilder chunk = new StringBuilder();
while (!stack.peek().equals("[")) {
chunk.insert(0, stack.pop());
}
stack.pop(); // drop "["
StringBuilder k = new StringBuilder();
while (!stack.isEmpty() && isDigit(stack.peek())) {
k.insert(0, stack.pop());
}
stack.push(chunk.toString().repeat(Integer.parseInt(k.toString())));
}
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) result.append(stack.pollLast());
return result.toString();
}
private boolean isDigit(String part) {
return part.length() == 1 && Character.isDigit(part.charAt(0));
}
}Decode String in C++
class Solution {
public:
string decodeString(string s) {
vector<string> stack;
for (char c : s) {
if (c != ']') {
stack.push_back(string(1, c));
} else {
string chunk = "";
while (stack.back() != "[") {
chunk = stack.back() + chunk;
stack.pop_back();
}
stack.pop_back(); // drop "["
string k = "";
while (!stack.empty() && stack.back().size() == 1 && isdigit(stack.back()[0])) {
k = stack.back() + k;
stack.pop_back();
}
string repeated = "";
for (int times = stoi(k); times > 0; times--) repeated += chunk;
stack.push_back(repeated);
}
}
string result = "";
for (const string& part : stack) result += part;
return result;
}
};Decode String in TypeScript
function decodeString(s: string): string {
const stack: string[] = [];
for (const ch of s) {
if (ch !== ']') {
stack.push(ch);
} else {
let chunk = '';
while (stack[stack.length - 1] !== '[') {
chunk = stack.pop()! + chunk;
}
stack.pop(); // drop "["
let k = '';
while (stack.length > 0 && /^\d$/.test(stack[stack.length - 1])) {
k = stack.pop()! + k;
}
stack.push(chunk.repeat(Number(k)));
}
}
return stack.join('');
}Decode String in C
static char* join(const char* a, const char* b) {
char* out = malloc(strlen(a) + strlen(b) + 1);
strcpy(out, a);
strcat(out, b);
return out;
}
char* decodeString(char* s) {
int n = strlen(s);
char** stack = malloc((n + 1) * sizeof(char*));
int top = 0;
for (int i = 0; i < n; i++) {
char ch = s[i];
if (ch != ']') {
char one[2] = { ch, '\0' };
stack[top++] = join(one, "");
} else {
char* chunk = join("", "");
while (strcmp(stack[top - 1], "[") != 0) {
char* next = join(stack[--top], chunk);
free(stack[top]);
free(chunk);
chunk = next;
}
free(stack[--top]); // drop "["
char* k = join("", "");
while (top > 0 && strlen(stack[top - 1]) == 1 && isdigit(stack[top - 1][0])) {
char* next = join(stack[--top], k);
free(stack[top]);
free(k);
k = next;
}
char* repeated = join("", "");
for (int times = atoi(k); times > 0; times--) {
char* next = join(repeated, chunk);
free(repeated);
repeated = next;
}
free(k);
free(chunk);
stack[top++] = repeated;
}
}
char* result = join("", "");
for (int j = 0; j < top; j++) {
char* next = join(result, stack[j]);
free(result);
free(stack[j]);
result = next;
}
free(stack);
return result;
}More practice: DSA interview questions with answers · patterns cheat sheet
