Longest Valid Parentheses
Longest Valid Parentheses is a hard dynamic programming problem solved with the strings pattern.
The best approach, optimal (two counting passes), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (every start) up.
Problem
You are given a string s made only of the characters '(' and ')'.
Return the length of the longest contiguous substring of s that is a balanced bracket sequence: every '(' is closed by a later ')', and no ')' appears before its matching '('.
Examples
Example 1
- Input
s = ")(()())("- Output
6- Why
- The middle part (()()) is balanced; the stray ) at the start and ( at the end are not.
Example 2
- Input
s = "()(()"- Output
2- Why
- The unmatched ( at index 2 splits the string, so the best balanced pieces are () and ().
Example 3
- Input
s = ""- Output
0- Why
- An empty string has no non-empty balanced substring.
Constraints
0 <= s.length <= 3 * 10^4s[i]is'('or')'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (every start) | O(n²) | O(1) |
| DP (longest ending here) | O(n) | O(n) |
| Optimal (two counting passes) | O(n) | O(1) |
1Brute force (every start)
O(n²)Each of the n starts can scan to the end.O(1)Only counters.For each start index, scan to the right keeping a balance counter (+1 for (, -1 for )). Every time the balance returns to zero, the substring so far is balanced; when it goes negative, nothing longer from this start can be balanced, so stop.
- For each i: bal = 0; for j from i: update bal with s[j].
- If bal < 0, break. If bal == 0, best = max(best, j - i + 1).
class Solution {
public int longestValidParentheses(String s) {
int n = s.length(), best = 0;
for (int i = 0; i < n; i++) {
int bal = 0;
for (int j = i; j < n; j++) {
bal += s.charAt(j) == '(' ? 1 : -1;
if (bal < 0) break;
if (bal == 0) best = Math.max(best, j - i + 1);
}
}
return best;
}
}class Solution:
def longestValidParentheses(self, s: str) -> int:
n, best = len(s), 0
for i in range(n):
bal = 0
for j in range(i, n):
bal += 1 if s[j] == '(' else -1
if bal < 0:
break
if bal == 0:
best = max(best, j - i + 1)
return bestclass Solution {
public:
int longestValidParentheses(string s) {
int n = s.size(), best = 0;
for (int i = 0; i < n; i++) {
int bal = 0;
for (int j = i; j < n; j++) {
bal += s[j] == '(' ? 1 : -1;
if (bal < 0) break;
if (bal == 0) best = max(best, j - i + 1);
}
}
return best;
}
};function longestValidParentheses(s) {
const n = s.length;
let best = 0;
for (let i = 0; i < n; i++) {
let bal = 0;
for (let j = i; j < n; j++) {
bal += s[j] === '(' ? 1 : -1;
if (bal < 0) break;
if (bal === 0) best = Math.max(best, j - i + 1);
}
}
return best;
}2DP (longest ending here)
O(n)Each index is filled in constant time.O(n)The dp array.dp[i] is the length of the longest balanced substring that ends at index i (0 if s[i] is '('). If s[i] is ')' and s[i-1] is '(', they pair up and extend whatever ended at i - 2. If s[i-1] is ')', a block of length dp[i-1] ends there; the character just before that block must be '(' to pair with s[i], and then the block ending right before that '(' joins on too.
- Skip indices where s[i] == '('.
- If s[i-1] == '(': dp[i] = 2 + dp[i-2] (0 if out of range).
- Else let j = i - dp[i-1] - 1; if j >= 0 and s[j] == '(': dp[i] = dp[i-1] + 2 + dp[j-1] (0 if out of range).
- Answer = max of dp.
class Solution {
public int longestValidParentheses(String s) {
int n = s.length(), best = 0;
int[] dp = new int[n];
for (int i = 1; i < n; i++) {
if (s.charAt(i) != ')') continue;
if (s.charAt(i - 1) == '(') {
dp[i] = 2 + (i >= 2 ? dp[i - 2] : 0);
} else {
int j = i - dp[i - 1] - 1;
if (j >= 0 && s.charAt(j) == '(')
dp[i] = dp[i - 1] + 2 + (j >= 1 ? dp[j - 1] : 0);
}
best = Math.max(best, dp[i]);
}
return best;
}
}class Solution:
def longestValidParentheses(self, s: str) -> int:
n, best = len(s), 0
dp = [0] * n
for i in range(1, n):
if s[i] != ')':
continue
if s[i - 1] == '(':
dp[i] = 2 + (dp[i - 2] if i >= 2 else 0)
else:
j = i - dp[i - 1] - 1
if j >= 0 and s[j] == '(':
dp[i] = dp[i - 1] + 2 + (dp[j - 1] if j >= 1 else 0)
best = max(best, dp[i])
return bestclass Solution {
public:
int longestValidParentheses(string s) {
int n = s.size(), best = 0;
vector<int> dp(n, 0);
for (int i = 1; i < n; i++) {
if (s[i] != ')') continue;
if (s[i - 1] == '(') {
dp[i] = 2 + (i >= 2 ? dp[i - 2] : 0);
} else {
int j = i - dp[i - 1] - 1;
if (j >= 0 && s[j] == '(')
dp[i] = dp[i - 1] + 2 + (j >= 1 ? dp[j - 1] : 0);
}
best = max(best, dp[i]);
}
return best;
}
};function longestValidParentheses(s) {
const n = s.length;
const dp = new Array(n).fill(0);
let best = 0;
for (let i = 1; i < n; i++) {
if (s[i] !== ')') continue;
if (s[i - 1] === '(') {
dp[i] = 2 + (i >= 2 ? dp[i - 2] : 0);
} else {
const j = i - dp[i - 1] - 1;
if (j >= 0 && s[j] === '(')
dp[i] = dp[i - 1] + 2 + (j >= 1 ? dp[j - 1] : 0);
}
best = Math.max(best, dp[i]);
}
return best;
}3Optimal (two counting passes)
O(n)Two linear scans.O(1)Four counters, no extra array or stack.Scan left to right counting open and close brackets. When they are equal, the stretch since the last reset is balanced; when close exceeds open, that stretch can never be fixed, so reset both counts. This misses stretches where opens stay ahead to the end (like (()), so do a second scan from right to left with the roles of the brackets swapped.
- Left to right: open++ or close++; if open == close, best = max(best, 2 · close); if close > open, reset both to 0.
- Right to left: same, but reset when open > close.
- Return best.
class Solution {
public int longestValidParentheses(String s) {
int n = s.length(), best = 0, open = 0, close = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '(') open++;
else close++;
if (open == close) best = Math.max(best, 2 * close);
else if (close > open) open = close = 0;
}
open = close = 0;
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == '(') open++;
else close++;
if (open == close) best = Math.max(best, 2 * open);
else if (open > close) open = close = 0;
}
return best;
}
}class Solution:
def longestValidParentheses(self, s: str) -> int:
best = open_ = close = 0
for ch in s:
if ch == '(':
open_ += 1
else:
close += 1
if open_ == close:
best = max(best, 2 * close)
elif close > open_:
open_ = close = 0
open_ = close = 0
for ch in reversed(s):
if ch == '(':
open_ += 1
else:
close += 1
if open_ == close:
best = max(best, 2 * open_)
elif open_ > close:
open_ = close = 0
return bestclass Solution {
public:
int longestValidParentheses(string s) {
int n = s.size(), best = 0, open = 0, close = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '(') open++;
else close++;
if (open == close) best = max(best, 2 * close);
else if (close > open) open = close = 0;
}
open = close = 0;
for (int i = n - 1; i >= 0; i--) {
if (s[i] == '(') open++;
else close++;
if (open == close) best = max(best, 2 * open);
else if (open > close) open = close = 0;
}
return best;
}
};function longestValidParentheses(s) {
const n = s.length;
let best = 0, open = 0, close = 0;
for (let i = 0; i < n; i++) {
if (s[i] === '(') open++;
else close++;
if (open === close) best = Math.max(best, 2 * close);
else if (close > open) open = close = 0;
}
open = close = 0;
for (let i = n - 1; i >= 0; i--) {
if (s[i] === '(') open++;
else close++;
if (open === close) best = Math.max(best, 2 * open);
else if (open > close) open = close = 0;
}
return best;
}Edge cases to test
- Empty string or a single character (answer 0)
- Only opening or only closing brackets (answer 0)
- Two balanced blocks next to each other, like ()(()) (they join into one)
- Extra opening brackets on the left, like ((() (a left-to-right count alone never sees balance)
Hints
Hint 1
A substring is balanced when its running count of ( minus ) never drops below zero and ends at zero.
Hint 2
Let dp[i] be the length of the longest balanced substring ending at index i. When s[i] is ')', look just before the block that ends at i - 1 for its partner '('.
Hint 3
With O(1) space: scan left to right counting ( and ); record a length whenever the counts match, and reset when ) wins. Then scan right to left with the roles swapped to catch extra ( on the left.
FAQ
What is the best time complexity for Longest Valid Parentheses?
Optimal (two counting passes) runs in O(n) time and O(1) extra space. Two linear scans.
Which pattern does Longest Valid Parentheses use?
It is a dynamic programming problem that uses the strings pattern. Other problems with the same pattern: Edit Distance, Longest Common Subsequence, Longest Palindromic Subsequence.
Is there a brute force solution for Longest Valid Parentheses?
Yes. Brute force (every start) takes O(n²) time and O(1) space. For each start index, scan to the right keeping a balance counter (+1 for (, -1 for )).
Which edge cases should I test for Longest Valid Parentheses?
Empty string or a single character (answer 0); Only opening or only closing brackets (answer 0); Two balanced blocks next to each other, like ()(()) (they join into one); Extra opening brackets on the left, like ((() (a left-to-right count alone never sees balance).