Practice › Stack & Queue
Longest Valid Parentheses
Hard · Stack & Queue · Asked at Amazon, Google, Microsoft, Meta
The string contains only ( and ). Print the length of the longest contiguous substring that is a valid (well-formed) parentheses string, or 0 if there is none.
Input
A single line with the string.
Output
The length of the longest valid substring.
Constraints
- 1 ≤ length ≤ 10^5
Keep a stack of indices, starting with −1 as a base. Push the index of every
(. On), pop; if the stack becomes empty, push this index as the new base, otherwise the valid length ending here is i − top.
Example 1
Input
(()
Output
2
Example 2
Input
)()())
Output
4
Example 3
Input
)(
Output
0
Hints
- A stack of indices can tell where the current valid run started.
- Keep a "base" index below the open brackets: the position just before the current run.
- When a ")" empties the stack, it becomes the new base.
Approach
Start the stack with −1. For "(", push its index. For ")", pop: if the stack is now empty, this ")" is unmatched — push its index as the new base; otherwise the run of valid parentheses ending here starts right after the index on top, so its length is i − top. Track the maximum.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
vector<int> st = {-1};
int best = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (s[i] == '(') st.push_back(i);
else {
st.pop_back();
if (st.empty()) st.push_back(i);
else best = max(best, i - st.back());
}
}
cout << best << "\n";
return 0;
}Python solution
s = input().strip()
stack = [-1]
best = 0
for i, c in enumerate(s):
if c == "(":
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
best = max(best, i - stack[-1])
print(best)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
int[] st = new int[s.length() + 1];
int top = 0, best = 0;
st[top++] = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') st[top++] = i;
else {
top--;
if (top == 0) st[top++] = i;
else best = Math.max(best, i - st[top - 1]);
}
}
System.out.println(best);
}
}Solve Longest Valid Parentheses online · All practice problems