FAANGPrep Sprint
Valid Parentheses (LeetCode 20)
Valid Parentheses (LeetCode 20): determine if the input string has valid matching brackets.
Problem Understanding
The string s is made only of the bracket characters (, ), {, }, [ and ]. Decide whether it is balanced.
It is balanced when:
- Every opening bracket is closed by a bracket of the same kind.
- Brackets close in reverse order of opening, so the most recently opened one closes first.
Example:
- Input:
s = "()[]{}"-> Output:true - Input:
s = "(]"-> Output:false - Input:
s = "([)]"-> Output:false
Algorithm Strategy
We use a Stack data structure.
- Iterate through the string char by char.
- If we see an open bracket (
(,{,[), push it onto the stack. - If we see a close bracket (
),},]), check the top of the stack:- If stack is empty, it's invalid (no matching open).
- If stack top is the matching open bracket, pop the stack.
- Otherwise, it's a mismatch -> invalid.
- At the end, stack must be empty (all opened brackets were closed).
Interactive Visualization
"({[]})"
READ
string
i
(
0
{
1
[
2
]
3
}
4
)
5
stack
empty
Open
0
Needs
:
Answer
:
Read '(' at 0
Next
'(' opens a group: push it. It must be closed before anything below it
String
Legend & Complexity
The character being read
Already matched
The top opener a closer is checked against
A closer with no matching opener on top
Time
O(n)
Space
O(n)
Watch how the stack grows with open brackets and shrinks with matching closed ones.
Dry Run
Input: ({[]})
| Step | Char | Action | Stack |
|---|---|---|---|
| 1 | ( |
Push | ( |
| 2 | { |
Push | ( { |
| 3 | [ |
Push | ( { [ |
| 4 | ] |
Match [? Yes. Pop. |
( { |
| 5 | } |
Match {? Yes. Pop. |
( |
| 6 | ) |
Match (? Yes. Pop. |
Empty |
| End | - | Stack Empty? Yes. | Valid |
Edge Cases & Common Mistakes
- Empty String: Usually valid (unless constraints say otherwise).
- Odd Length: Automatically invalid.
- Start with Close:
]...invalid immediately. - Leftovers:
(()stack not empty at end.
Solution
Stack implementation.
Valid Parentheses Code
1var isValid = function(s) {2 const stack = [];3 const pairs = { ')': '(', ']': '[', '}': '{' };4 for (const ch of s) {5 if (!(ch in pairs)) {6 stack.push(ch);7 } else if (stack.length === 0 || stack[stack.length - 1] !== pairs[ch]) {8 return false;9 } else {10 stack.pop();11 }12 }13 return stack.length === 0;14};
Valid Parentheses in Python, Java, C++, TypeScript and C
Valid Parentheses in Python
class Solution:
def isValid(self, s: str) -> bool:
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for ch in s:
if ch not in pairs:
stack.append(ch)
elif not stack or stack[-1] != pairs[ch]:
return False
else:
stack.pop()
return not stackValid Parentheses in Java
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');
for (char ch : s.toCharArray()) {
if (!pairs.containsKey(ch)) {
stack.push(ch);
} else if (stack.isEmpty() || !stack.peek().equals(pairs.get(ch))) {
return false;
} else {
stack.pop();
}
}
return stack.isEmpty();
}
}Valid Parentheses in C++
class Solution {
public:
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> pairs = {{')', '('}, {']', '['}, {'}', '{'}};
for (char ch : s) {
if (!pairs.count(ch)) {
st.push(ch);
} else if (st.empty() || st.top() != pairs[ch]) {
return false;
} else {
st.pop();
}
}
return st.empty();
}
};Valid Parentheses in TypeScript
function isValid(s: string): boolean {
const stack: string[] = [];
const pairs: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
for (const ch of s) {
if (!(ch in pairs)) {
stack.push(ch);
} else if (stack.length === 0 || stack[stack.length - 1] !== pairs[ch]) {
return false;
} else {
stack.pop();
}
}
return stack.length === 0;
}Valid Parentheses in C
bool isValid(char* s) {
int n = strlen(s);
char* stack = malloc(n + 1);
int top = 0;
for (int i = 0; i < n; i++) {
char ch = s[i];
char open = ch == ')' ? '(' : ch == ']' ? '[' : ch == '}' ? '{' : 0;
if (!open) {
stack[top++] = ch;
} else if (top == 0 || stack[top - 1] != open) {
free(stack);
return false;
} else {
top--;
}
}
bool valid = top == 0;
free(stack);
return valid;
}