Valid Parentheses
Problem Link
20. Valid Parentheses – LeetCode
Problem Statement
Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.
A string is valid if:
-
Open brackets are closed by the same type of brackets.
-
Open brackets are closed in the correct order.
Examples
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints
-
1 <= s.length <= 10⁴ -
sconsists of parentheses only:'()[]{}'
Intuition
The problem is based on balanced brackets. A valid parentheses string must maintain:
-
Matching pairs for every opening bracket.
-
Correct nesting and closing order.
A stack is ideal for this, because it follows Last-In-First-Out (LIFO) behavior:
-
Push opening brackets.
-
For closing brackets, pop and check for correct pairing.
Approach: Stack-Based Matching
-
Traverse the input string character by character.
-
If the character is an opening bracket, push it to the stack.
-
If it's a closing bracket:
-
Check if the stack is empty → if yes, return false.
-
Check the top of the stack:
-
If it's a matching opening bracket, pop it.
-
If not, return false.
-
-
-
After the loop, return true only if the stack is empty (all brackets matched).
Java Code
class Solution {
public boolean isValid(String s) {
if (s.charAt(0) == '}' || s.charAt(0) == ')' || s.charAt(0) == ']') return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else {
if (stack.isEmpty()) return false;
char top = stack.peek();
if ((ch == ')' && top == '(') ||
(ch == ']' && top == '[') ||
(ch == '}' && top == '{')) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
}
Time and Space Complexity
| Metric | Value |
|---|---|
| Time Complexity | O(n) |
| Space Complexity | O(n) |
| Explanation | Stack holds at most n characters in worst case |
Dry Run
Input:
s = "{[()]}"
Stack State:
-
{→ push →[{] -
[→ push →[{ [ ] -
(→ push →[{ [ ( ] -
)→ match with(→ pop -
]→ match with[→ pop -
}→ match with{→ pop
Stack is empty → valid.
Output:
true
Follow-Up
To generalize or optimize:
-
Use a HashMap for bracket pairs (
{')': '(', ']': '[', '}': '{'}) to avoid repetitive if-else conditions. -
Use Deque (
ArrayDeque) for faster stack operations in Java.
Conclusion
This problem is a foundational example of stack-based validation, especially useful in:
-
Parsing expressions
-
Validating XML/HTML
-
Compiler design