Problem Statement
Given a string containing only:
(
)
[
]
{
}
Determine whether the parentheses are valid.
A string is valid if:
- Every opening bracket has a matching closing bracket.
- Brackets close in the correct order.
Brute Force Intuition
In an interview, you can explain it like this:
We can repeatedly scan the string and remove valid pairs like
(),{}, and[]. If the string eventually becomes empty, it's valid.
However, this requires repeatedly traversing the string.
Complexity
- Time Complexity: O(N²)
- Space Complexity: O(N)
Brute Force Code
class Solution {
public boolean isValid(String s) {
while (true) {
String reduced = s.replace("()", "")
.replace("[]", "")
.replace("{}", "");
if (reduced.equals(s))
break;
s = reduced;
}
return s.isEmpty();
}
}
Moving Towards the Optimal Approach
Notice something important.
Whenever we encounter:
Opening Bracket
we don't know when it will close.
So we need to remember it.
Which data structure remembers the most recent element?
Stack
Pattern Recognition
Whenever you see:
- Matching Brackets
- Nested Structures
- Reverse Order Processing
Think:
Stack
Key Observation
For every character:
Opening Bracket
Push into Stack
Closing Bracket
Top should contain
its matching opening bracket.
If:
- Stack is empty
- Top doesn't match
Return:
false
Optimal Java Solution
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else if (c == ')') {
if (st.isEmpty() || st.peek() != '(')
return false;
st.pop();
} else if (c == ']') {
if (st.isEmpty() || st.peek() != '[')
return false;
st.pop();
} else {
if (st.isEmpty() || st.peek() != '{')
return false;
st.pop();
}
}
return st.isEmpty();
}
}
Dry Run
Input
s = "{[()]}"
Step 1
{
Push
Stack:
{
Step 2
[
Push
Stack:
[
{
Step 3
(
Push
Stack:
(
[
{
Step 4
)
Top = (
Match ✓
Pop
Stack:
[
{
Step 5
]
Top = [
Match ✓
Pop
Stack:
{
Step 6
}
Top = {
Match ✓
Pop
Stack:
Empty
Answer:
true
Why Stack Works?
The most recently opened bracket must be closed first.
Example:
{ [ ( ) ] }
The closing order is exactly the reverse of the opening order.
This is the LIFO (Last In, First Out) property of a Stack.
Complexity Analysis
| Metric | Complexity |
|---|---|
| Time Complexity | O(N) |
| Space Complexity | O(N) |
Interview One-Liner
Push every opening bracket onto the stack. For each closing bracket, ensure it matches the stack's top. If every bracket matches and the stack is empty at the end, the string is valid.
Pattern Learned
Matching Symbols
+
Nested Structure
+
Reverse Closing Order
=> Stack
Similar Problems
- Valid Parentheses
- Remove Outermost Parentheses
- Minimum Remove to Make Valid Parentheses
- Longest Valid Parentheses
- Decode String
Memory Trick
Think:
Opening Bracket
↓
Push
Closing Bracket
↓
Matches Top ?
Yes → Pop
No → Invalid
Mental Model
Open
↓
Remember
↓
Close
↓
Match
↓
Remove
Whenever you hear:
"Validate brackets" or "Matching parentheses"
your brain should immediately think:
Stack (LIFO) 🚀
Top comments (0)