Home
DSA Patterns
Stack
Longest Valid Parentheses
Longest Valid Parentheses (LeetCode 32)
Longest Valid Parentheses (LeetCode 32): measure the longest stretch of a bracket string in which every parenthesis is matched.
Problem Understanding
The input string contains only ( and ). Return the length of the longest contiguous stretch in which every bracket is correctly matched and nested.
Example:
- Input:
(()-> Output:2(substring()). - Input:
)()())-> Output:4(substring()()).
Algorithm Strategy
We can use a Stack to store indices. The stack will help us calculate the length of valid substrings by tracking the 'base' index from which validity starts.
- Initialize stack with
-1. This acts as a base index for a valid substring starting at 0. - Iterate through string at index
i: - If
(:push(i). - If
):pop().- If stack is empty:
push(i). The current)is invalid and becomes the new base. - If stack not empty:
maxLen = max(maxLen, i - stack.top()). The valid substring is fromstack.top() + 1toi.
- If stack is empty:
Interactive Visualization
")()())"
BASE -1
string
0
1
2
3
4
5
stack · indices
TOP · base
Run
:
Best
0
Start the stack with -1: the base a valid run starting at index 0 measures from
Next
')' at 0: pop -1, the old base
String
Visualize how storing indices helps calculate length. -1 is our initial base.
Dry Run
Input: )()())
| Idx | Char | Action | Stack | MaxLen |
|---|---|---|---|---|
| - | - | Init | [-1] |
0 |
| 0 | ) |
Pop -1. Stack empty. Push 0. | [0] |
0 |
| 1 | ( |
Push 1. | [0, 1] |
0 |
| 2 | ) |
Pop 1. Len = 2-0 = 2. | [0] |
2 |
| 3 | ( |
Push 3. | [0, 3] |
2 |
| 4 | ) |
Pop 3. Len = 4-0 = 4. | [0] |
4 |
| 5 | ) |
Pop 0. Stack empty. Push 5. | [5] |
4 |
Edge Cases & Common Mistakes
- Empty String: Length 0.
- All Open:
((((-> Length 0. - Initial Close:
)-> Resets base. - Base -1: Needed for substrings starting at index 0.
Solution
Stack Logic O(N) Time O(N) Space.
Longest Valid Parentheses Code
1var longestValidParentheses = function(s) {2 const stack = [-1];3 let maxLen = 0;4 for (let i = 0; i < s.length; i++) {5 if (s[i] === '(') {6 stack.push(i);7 } else {8 stack.pop();9 if (stack.length === 0) {10 stack.push(i);11 } else {12 maxLen = Math.max(maxLen, i - stack[stack.length - 1]);13 }14 }15 }16 return maxLen;17};
Longest Valid Parentheses in Python, Java, C++, TypeScript and C
Longest Valid Parentheses in Python
class Solution:
def longestValidParentheses(self, s: str) -> int:
stack = [-1]
max_len = 0
for i, char in enumerate(s):
if char == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
return max_lenLongest Valid Parentheses in Java
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
return maxLen;
}
}Longest Valid Parentheses in C++
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int maxLen = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
st.push(i);
} else {
st.pop();
if (st.empty()) {
st.push(i);
} else {
maxLen = max(maxLen, i - st.top());
}
}
}
return maxLen;
}
};Longest Valid Parentheses in TypeScript
function longestValidParentheses(s: string): number {
const stack: number[] = [-1];
let maxLen = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
stack.push(i);
} else {
stack.pop();
if (stack.length === 0) {
stack.push(i);
} else {
maxLen = Math.max(maxLen, i - stack[stack.length - 1]);
}
}
}
return maxLen;
};Longest Valid Parentheses in C
int longestValidParentheses(char * s) {
int n = strlen(s);
int* stack = (int*)malloc((n + 1) * sizeof(int));
int top = -1;
stack[++top] = -1;
int maxLen = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '(') {
stack[++top] = i;
} else {
top--;
if (top == -1) {
stack[++top] = i;
} else {
int len = i - stack[top];
if (len > maxLen) maxLen = len;
}
}
}
free(stack);
return maxLen;
}More practice: DSA interview questions with answers · patterns cheat sheet
