You are given an encoded string following the pattern k[encoded_string], where k is a positive integer indicating how many times the content inside the brackets should be repeated. The brackets can be nested, meaning you must decode the innermost brackets first.
Two stacks provide a clean solution: one stack for repeat counts and one stack for partial results. When you encounter a number, build the full count. When you encounter [, push the current count and current decoded string onto their stacks, then reset both. When you encounter ], pop the count and previous string, repeat the current decoded string count times, and append it to the previous string.
For example, "3[a]2[bc]" → "aaabcbc". "3[a2[c]]" → inner 2[c] becomes "cc", then 3[acc] → "accaccacc".
Example Input & Output
Inner 2[c] = cc. Outer 3[acc] = accaccacc.
2[abc]=abcabc, 3[cd]=cdcdcd, then +ef.
3[a] = aaa, 2[bc] = bcbc. Combined: aaabcbc.
3[cd]=cdcdcd inserted between abc and xyz.
Algorithm Flow

Solution Approach
Use two stacks: countStack and resultStack. Iterate through each character. If it's a digit, build the full number. If it's [, push the current count and current result, then reset both. If it's ], pop count and previous result, repeat the current result count times, and append to previous. Otherwise, it's a letter, append to current result.
Time complexity is O(n * k) where k is the max repeat count. Space complexity is O(n) for the stacks.
Best Answers
import java.util.*;
class Solution {
public String solution(String s) {
Stack<Integer> countStack = new Stack<>();
Stack<String> resultStack = new Stack<>();
String result = "";
int i = 0;
while (i < s.length()) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') {
int num = 0;
while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
num = num * 10 + (s.charAt(i) - '0'); i++;
}
countStack.push(num);
} else if (ch == '[') { resultStack.push(result); result = ""; i++; }
else if (ch == ']') {
int repeat = countStack.pop();
String temp = resultStack.pop();
for (int j = 0; j < repeat; j++) temp += result;
result = temp; i++;
} else { result += ch; i++; }
}
return result;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
