Longest Valid Parentheses solution explained

Longest Valid Parentheses asks for the length of the longest substring of '(' and ')' characters that is correctly balanced. Push indexes onto a stack, starting with a sentinel -1: an opening bracket pushes its index, a closing bracket pops, and if the stack is then empty its index becomes the new barrier; otherwise the valid run ends here and its length is the current index minus the index on top of the stack. One pass, O(n) time.

By Published 7 min read

The problem, restated

The input contains only '(' and ')'. A substring is valid when every ')' closes an earlier '(' inside the same substring and nothing is left open at the end. Return the length of the longest valid substring, or 0 if there is none. Note that the answer must be contiguous: you cannot skip characters.

For the string )(()())(() the answer is 6, from index 1 to 6: (()()). The stray ')' at the start can never be matched, and the (() at the end contains a valid pair of length 2 but no more.

Why this is not a sliding window

It looks like one: a contiguous substring, a longest-valid question. But the sliding window pattern needs validity to be monotone, so that once a window breaks, growing it further cannot fix it. Here, (( is invalid and (()) is valid; growing repaired it. Shrinking from the left is not safe either. Saying this early shows the interviewer you are choosing a technique for a reason, not by keyword.

Brute force with a running balance

def longest_valid_brute(s):
    """Check every substring with a balance counter: O(n^2)."""
    best = 0
    for i in range(len(s)):
        balance = 0
        for j in range(i, len(s)):
            balance += 1 if s[j] == "(" else -1
            if balance < 0:
                break                      # a ')' with no partner: stop extending
            if balance == 0:
                best = max(best, j - i + 1)
    return best
Every start, extended to the right while the balance stays non-negative. O(n²).

Checking each substring from scratch would be O(n³). Keeping a running balance as you extend from a fixed start brings it to O(n²): the balance going negative means a ')' has no partner, and no longer substring from this start can be valid, so you stop. Every time the balance returns to zero, the substring so far is valid.

One pass with a stack of indexes

The stack holds indexes, not characters. Its bottom element is always the index just before the current candidate run, a barrier the run cannot cross. Above it sit the indexes of '(' still waiting for partners. When a ')' arrives, pop. If something remains, the run from just after the new top to here is valid, so its length is i minus the top. If nothing remains, this ')' was unmatched; it becomes the new barrier.

def longest_valid_stack(s):
    """Stack of indexes; the bottom is the last position that cannot be crossed."""
    stack = [-1]
    best = 0
    for i, ch in enumerate(s):
        if ch == "(":
            stack.append(i)
        else:
            stack.pop()
            if not stack:
                stack.append(i)            # unmatched ')': new barrier
            else:
                best = max(best, i - stack[-1])
    return best
O(n) time, O(n) memory. The -1 sentinel makes a run starting at index 0 measure correctly.
#include <algorithm>
#include <string>
#include <vector>

int longestValid(const std::string& s) {
    std::vector<int> stack{-1};
    int best = 0;
    for (int i = 0; i < static_cast<int>(s.size()); ++i) {
        if (s[i] == '(') {
            stack.push_back(i);
        } else {
            stack.pop_back();
            if (stack.empty()) {
                stack.push_back(i);
            } else {
                best = std::max(best, i - stack.back());
            }
        }
    }
    return best;
}
The same pass in C++17, with a vector as the stack.

A stack trace

Running the stack version on )(()())(() (printed by the code)
icharstack afterwhat happened
0)[0]pop -1, empty: index 0 is the new barrier
1([0, 1]push
2([0, 1, 2]push
3)[0, 1]pop 2; run length 3 - 1 = 2
4([0, 1, 4]push
5)[0, 1]pop 4; run length 5 - 1 = 4
6)[0]pop 1; run length 6 - 0 = 6, the answer
7([0, 7]push
8([0, 7, 8]push
9)[0, 7]pop 8; run length 9 - 7 = 2
Running the stack version on )(()())(() (printed by the code). Scroll sideways on a small screen.

Constant memory: two counter passes

Scan left to right counting opens and closes. When they are equal, you have a balanced run of twice the count. When closes exceed opens, the run is dead, so reset both to zero. That pass misses runs like ((() where opens stay ahead to the end. A second scan from the right, with the roles of the brackets swapped, catches exactly those. The answer is the larger of the two passes.

def longest_valid_two_pass(s):
    """Count opens and closes left to right, then right to left. O(1) space."""
    def scan(chars, opener):
        best = opens = closes = 0
        for ch in chars:
            if ch == opener:
                opens += 1
            else:
                closes += 1
            if opens == closes:
                best = max(best, 2 * closes)
            elif closes > opens:
                opens = closes = 0          # reset after an impossible prefix
        return best
    return max(scan(s, "("), scan(reversed(s), ")"))
O(n) time, O(1) extra memory.

Cost

n = length of the string
ApproachTimeExtra memory
Check every substring from scratchO(n³)O(1)
Running balance per startO(n²)O(1)
Stack of indexesO(n)O(n)
DP over end positionsO(n)O(n)
Two counter passesO(n)O(1)
n = length of the string. Scroll sideways on a small screen.

The DP version stores, for each index, the length of the longest valid run ending there; a ')' extends either the pair just before it or a run that ended one step before its partner. It is also O(n) and a fine answer, but the stack version is easier to get right under time pressure.

Edge cases

  • Empty string: 0.
  • Only opening or only closing brackets: 0.
  • A wrong-order pair )(: 0.
  • Two valid runs touching, such as ()(()): they join into one run of 6, and the stack handles that because the barrier does not move.
  • Unmatched opens on the left of a valid run, as in the string ((() (extra opens before a valid pair): the left-to-right counter pass misses it; the stack and the reverse pass do not.

Where answers go wrong

  • Counting matched pairs across the whole string instead of the longest contiguous run.
  • Pushing characters instead of indexes, which leaves no way to measure length.
  • Forgetting the -1 sentinel, so a valid run starting at index 0 is measured one short or crashes on an empty stack.
  • Doing only the left-to-right counter pass.
  • Trying a sliding window and patching it with special cases until it passes the examples but not the edge cases.

How to explain it out loud

Fictional example

Explaining the barrier
Candidate
A window will not work here, because a run can become valid by growing. I will use a stack of indexes instead.
Candidate
The bottom of the stack is a barrier: the last position a valid run cannot extend past. I start it at -1. Opens push their index; a close pops. If the stack still has something, the run from after the top to here is valid and its length is i minus the top.
Interviewer
And if the stack is empty after the pop?
Candidate
Then this close had no partner, so nothing valid can cross it. I push its index as the new barrier. One pass, O(n) time and space; there is also a two-pass counter version if you want O(1) memory.

Same idea, other problems

  • Fewest insertions to make a bracket string valid. A running balance; count the times it would go negative and what is left open at the end.
  • Remove the fewest brackets so the string is valid. A stack of indexes to find unmatched positions, then skip them.
  • Longest balanced substring of two letters with equal counts. A running difference stored in a hash map of first positions.

Valid Parentheses is the warm-up: decide whether the whole string is balanced, with several bracket types. Maximal Square is a grid DP for comparison, and Regular Expression Matching is the next string problem in this set. The coding problems hub lists them all.

Rehearsing this one with Natively

This is a problem where candidates lose time trying the wrong technique. In a mock round, Natively keeps a transcript on your Mac or Windows computer, which makes it easy to see how long you spent on a window before switching to the stack. While studying, you can screenshot the prompt and ask it to argue for or against a sliding window before you write anything. See the coding interview assistant page for the details.

Questions people ask

How do you solve Longest Valid Parentheses?

Keep a stack of indexes starting with -1. Push the index of each '('. For each ')', pop; if the stack is empty, push this index as a new barrier, otherwise the valid run length is the index minus the stack's top.

Can Longest Valid Parentheses be solved with a sliding window?

Not directly. Validity is not monotone: an invalid substring can become valid as it grows, so shrinking from the left is not safe.

Is there an O(1) space solution?

Yes. Count opens and closes left to right, resetting when closes exceed opens, then repeat right to left with the roles swapped, and take the best balanced length.

What is the time complexity?

O(n) for the stack and the two-pass versions; the simple check from every start with a running balance is O(n²).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP