Balanced Parentheses Stack Java | Fresher Interview
Fast recall
Quick revision
Core answer
Whether you map nested brackets to a stack and handle empty-stack and leftover-stack cases
Forgetting to check the stack is empty at the end, or popping an empty stack on a closing bracket
Use a map of close->open and check both the mismatch and the empty-at-end conditions
Interview-ready guide
Interview answer
This is a textbook stack problem, and the reason a stack fits so naturally is that brackets have to close in the reverse order they were opened, the most recently opened bracket must close first, which is exactly the last-in, first-out behavior of a stack.
So I scan the string left to right. Every time I see an opening bracket, a round, square, or curly one, I push it onto the stack. Every time I see a closing bracket, I need to confirm that the most recent unclosed opener matches it.
So I check the top of the stack, and there are two ways it can fail right there: if the stack is empty when I hit a closing bracket, there's nothing for it to match, so it's invalid, and if the bracket I pop isn't the correct matching opener, the types or order are wrong, so it's also invalid. If it matches, I pop it and continue.
After I've scanned the entire string, there's one final check that freshers often forget: the stack must be empty. If there are leftover opening brackets on the stack, like in a string of three open parentheses, those were never closed, so the string is invalid. The whole thing is O of n time and O of n space.
I usually keep a small map from each closing bracket to its matching opener to make the comparison clean. And I'd note that simply counting brackets only works if there's a single bracket type; with mixed types you genuinely need the stack to track order.
Balanced Parentheses Stack Java | Fresher Interview
Direct Answer
Use a stack. Scan the string: push every opening bracket; on a closing bracket, pop and check it matches the expected opener - if it doesn't match (or the stack is empty), the string is invalid. At the end, the stack must be empty. O(n) time, O(n) space. The stack naturally enforces the innermost-must-close-first (LIFO) rule.
Deep Dive & Architecture
Scan the expression from left to right. Push every opening bracket. For a closing bracket, the most recently opened bracket must be on top of the stack and must be its matching type.
Worked example: {[()]}
Push {, [, and (. The next character is ), which matches (, so pop it. Then ] matches [ and } matches {. The scan ends with an empty stack, so the expression is balanced.
There are two immediate failure cases. A closing bracket with an empty stack has no opener—for example ]abc. A closing bracket that does not match the top opener breaks nesting—for example ([)]: when ) arrives, [ is on top. After the scan, a non-empty stack means some opening brackets were never closed, as in (().
Ignoring non-bracket characters is fine when the input is an expression, but the accepted character rules should be clear. A mapping from closing to opening symbols keeps the comparison readable.
Each bracket is pushed and popped at most once, so time is O(n). In the worst case, all characters are opening brackets, so the stack uses O(n) space. ArrayDeque<Character> is preferred to the legacy Stack class for this LIFO work in modern Java.
Code Example
boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
Map<Character,Character> close = Map.of(')','(', ']','[', '}','{');
for (char c : s.toCharArray()) {
if (close.containsValue(c)) stack.push(c); // opener
else if (close.containsKey(c)) { // closer
if (stack.isEmpty() || stack.pop() != close.get(c)) return false;
}
}
return stack.isEmpty(); // leftover openers => invalid
}
// "([])": push ( , push [ , ] pops [ ok, ) pops ( ok, empty -> true
// "([)]": ) pops [ -> mismatch -> false
Common Mistakes & Pitfalls
- No empty-at-end check:
"((("leaves openers on the stack - must verify it's empty. - Popping an empty stack: a closer with an empty stack (
")") is invalid - check first. - Ignoring bracket type:
"[)"has equal counts but wrong types - compare the actual opener. - Counting only: a counter works for one bracket type but fails for mixed types/order.
Check your understanding
Answer these without looking back at the article.
- What is a stack and what are its core operations?
- What is a queue and how does it differ from a stack?
- What are the real-world use cases of Stack and Queue in software engineering?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.