Longest Valid Parentheses

Hard Dynamic Programming Strings Original on LeetCode

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^4
  • s[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.

00:00
Testcase

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.

ApproachTimeSpace
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)

TimeO(n²)Each of the n starts can scan to the end.
SpaceO(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.

  1. For each i: bal = 0; for j from i: update bal with s[j].
  2. 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;
    }
}

2DP (longest ending here)

TimeO(n)Each index is filled in constant time.
SpaceO(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.

  1. Skip indices where s[i] == '('.
  2. If s[i-1] == '(': dp[i] = 2 + dp[i-2] (0 if out of range).
  3. 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).
  4. 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;
    }
}

3Optimal (two counting passes)

TimeO(n)Two linear scans.
SpaceO(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.

  1. Left to right: open++ or close++; if open == close, best = max(best, 2 · close); if close > open, reset both to 0.
  2. Right to left: same, but reset when open > close.
  3. 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;
    }
}

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).