Decode String
Handle nested patterns like '3[a2[bc]]'. When you hit '[', push the current string and number onto the stack. When you hit ']', pop and repeat the current string that many times, then append to the previous string.
How It Works
Strings like "3[a2[bc]]" nest repetition inside repetition, so an inner group must be fully expanded before its enclosing group — a LIFO dependency. Maintain a current string and a current count. On a digit, accumulate the number (it may be multi-digit). On '[', push both the string built so far and the count onto a stack, then reset them. On ']', pop: the new current string becomes popped-string plus current-string repeated popped-count times. Regular letters simply append.
Each character is processed once and each expansion writes each output character once, so the time is O(n + output length). Recursion gives an equivalent solution where the call stack replaces the explicit one.
Step-by-Step Visualization
Code
static String decodeString(String s) {
Stack<Object[]> stack = new Stack<>();
StringBuilder curr = new StringBuilder();
int num = 0;
for (char ch : s.toCharArray()) {
if (ch >= '0' && ch <= '9') {
num = num * 10 + (ch - '0');
} else if (ch == '[') {
stack.push(new Object[]{curr.toString(), num});
curr = new StringBuilder(); num = 0;
} else if (ch == ']') {
Object[] top = stack.pop();
String prev = (String) top[0];
int count = (int) top[1];
StringBuilder repeated = new StringBuilder(prev);
for (int i = 0; i < count; i++) repeated.append(curr);
curr = repeated;
} else {
curr.append(ch);
}
}
return curr.toString();
}
// Example: decodeString("3[a2[c]]") → "accaccacc"Tips & Gotchas
Practice Problems
- 1Decode String
- 2Number of Atoms
- 3Basic Calculator III
- 4Brace Expansion
About the Parentheses / Matching Pattern
Stacks naturally handle nested structures. Push opening symbols, pop when you find their closing match. If the stack is empty at the end and every match was correct, the expression is valid.
Monotonic stacks are the power tool here. If you need 'next greater/smaller element' or 'span' queries, a monotonic stack gives O(n) instead of O(n²).
Common Stack Interview Problems
- Valid Parentheses
- Next Greater Element
- Largest Rectangle in Histogram
- Trapping Rain Water
- Daily Temperatures
- Decode String
Frequently Asked Questions
Why push two things at every opening bracket?
The '[' suspends an in-progress context: the prefix text already built and the multiplier that will apply to the bracketed group. Both must be restored exactly when the matching ']' arrives, so they are saved together — either as a pair on one stack or on two parallel stacks.
Is the recursive solution better than the iterative stack?
They are equivalent in complexity; recursion just uses the call stack implicitly and often reads more naturally. The iterative version avoids stack-overflow risk on pathologically deep nesting and makes the saved state explicit, which some interviewers prefer.
What is the most common bug in this problem?
Handling multi-digit counts like '12[ab]'. You must accumulate digits with count = count * 10 + digit rather than treating each digit as its own number, and reset the count to zero right after pushing it.