Valid Parentheses in Java Using Stack
Check whether a string of brackets is correctly opened and closed.
- Time
O(n) - Space
O(n) - Hints3
- Read2 min
Go through the string one character at a time. For each opening bracket, push the closing bracket you expect onto a stack. For each closing bracket, pop the stack and check that it is the same. The string is valid if every check passes and the stack is empty at the end. This takes O(n) time.
Problem statement
This is the classic valid parentheses Java question. You get a string made only of
(, ), [, ], { and }. Return true if:
- every opening bracket is closed by the same type, and
- brackets are closed in the right order (the last one opened is closed first).
A string s made only of the six bracket characters.
true if the brackets are valid, otherwise false.
Examples
s = {[()]}trueEach closing bracket matches the one opened most recently.
s = ([)]falseThe ) arrives while [ is still open.
s = ((falseTwo brackets are never closed.
Constraints
- 0 <= length of s <= 10^5
- An empty string counts as valid
Think before you code
Reveal the questions to ask yourself first
- When you meet a closing bracket, which open bracket must it match?
- Which data structure gives back the most recent item first?
- What does it mean if items are left over at the end?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Create an empty stack. Use
ArrayDeque: the Java documentation recommends aDequeover the oldStackclass. - For each opening bracket, push its matching closing bracket.
- For each closing bracket:
- If the stack is empty, nothing is open. Return
false. - Pop the stack. If it is not this bracket, return
false.
- If the stack is empty, nothing is open. Return
- After the loop, return whether the stack is empty.
New to stacks? Start with data structures and algorithms. The collections framework page gives the wider picture of Java collections.
Dry run
Walk through the example step by step
Checking {[()]}. The top of the stack is on the left:
char | action | stack
-----+-----------------------+--------
{ | push } | }
[ | push ] | ] }
( | push ) | ) ] }
) | pop ), it matches | ] }
] | pop ], it matches | }
} | pop }, it matches | empty
end | stack is empty | true
Solution
Reveal the full Java solution
import java.util.ArrayDeque;
import java.util.Deque;
public class ValidParentheses {
public static boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '[') {
stack.push(']');
} else if (c == '{') {
stack.push('}');
} else if (stack.isEmpty() || stack.pop() != c) {
return false; // nothing open, or the wrong one is open
}
}
return stack.isEmpty(); // anything left was never closed
}
public static void main(String[] args) {
System.out.println(isValid("{[()]}")); // true
System.out.println(isValid("([)]")); // false
System.out.println(isValid("((")); // false
}
}This is valid parentheses Java using stack. The stack always shows what must be closed next. Pushing the expected closing bracket keeps the valid parentheses Java code short: no lookup table is needed.
stack.pop() != c compares a Character with a char. Java turns the Character
into a plain char first, so the values are compared correctly.
Valid parentheses Java without stack
Only one type of bracket: a counter is enough. Add 1 for (, take away 1 for ).
It must never go below 0 and must end at 0.
// Only for strings made of ( and )
static boolean isValidRound(String s) {
int open = 0;
for (char c : s.toCharArray()) {
open += (c == '(') ? 1 : -1;
if (open < 0) return false; // closed before it was opened
}
return open == 0;
}
It gives true for (()()) and false for ())(.
All three types: keep removing neighbouring pairs until nothing changes.
// Handles all three types, but slower: O(n^2)
static boolean isValidByRemoving(String s) {
int before;
do {
before = s.length();
s = s.replace("()", "").replace("[]", "").replace("{}", "");
} while (s.length() < before);
return s.isEmpty();
}
This is easy to read but slow on long, deeply nested strings. In an interview, give the
valid parentheses Java stack answer first and mention this as another idea. Separate
counters for the three types do not work: they would accept ([)].
Practise next
After this valid parentheses program in Java, try reverse a linked list, and read the DSA interview questions. For guided practice, see the Java full stack course.
O(n)O(n)Review before the interview
Common mistakes
- Returning true at the end without checking that the stack is empty. This accepts ((.
- Calling pop on an empty stack. It throws an exception for input such as ).
- Only counting brackets. Counts miss wrong order, such as ([)].
Edge cases to test
- An empty string is valid.
- A string that starts with a closing bracket is invalid.
- An odd-length string can never be valid.
Interview follow-ups
- How would you skip letters and digits inside the string?
- How would you return the position of the first wrong bracket?
- How many brackets must be added to make a string valid?
Keep practising
Check Whether a String Is a Palindrome
Hints · Dry run · SolutionSolve Similar problemFind the First Non-Repeating Character in a String
Hints · Dry run · SolutionSolve Similar problemCheck Whether Two Strings Are Anagrams
Hints · Dry run · SolutionSolve Related learningStrings
TutorialLearn Related learningCollections Framework
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
