Longest Valid Parentheses (LeetCode 32): Solution and Explanation
Given a string made only of opening and closing parentheses, find the length of the longest contiguous substring that is a correctly balanced parentheses sequence.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force checks every substring for validity, which is O(n³), or O(n²) with a running balance. You want a single pass, and the natural tool for matching parentheses is a stack.
The usual matching stack holds positions of unmatched opening parentheses. When a closing parenthesis matches, the valid substring that just ended stretches back to the position right after whatever is now on top of the stack, because that top element is the nearest thing that is still unmatched. So the length is the current index minus the index on top of the stack. That means you should push indices, not characters.
The remaining question is what sits at the bottom of the stack. Seed it with -1, a sentinel meaning the valid region could start at index 0. When a closing parenthesis arrives and popping empties the stack, that closing parenthesis is unmatched and acts as a wall: nothing valid can cross it. Push its index as the new base, so later lengths are measured from just after it. With that one invariant (the bottom of the stack is always the last unmatched closing parenthesis, or -1), every length comes from a simple subtraction.
Approach: Stack of indices with a base sentinel
- Initialize
stack = [-1]andmax_len = 0. - For each index
i, ifs[i]is an opening parenthesis, pushi. - Otherwise pop the top of the stack, which matches this closing parenthesis or removes the base.
- If the stack is now empty, this closing parenthesis is unmatched, so push
ias the new base. - If the stack is not empty, update
max_lenwithi - stack[-1]. - Return
max_lenafter the scan.
Step-by-step example
s = ")()())"
- Index 0 is a closing parenthesis. Popping -1 empties the stack, so 0 is pushed as the new base: stack
[0]. - Index 1 is an opening parenthesis, so the stack becomes
[0, 1]. - Index 2 closes it: pop 1, the stack is
[0]and the length is 2 - 0 = 2. - Index 3 opens: stack
[0, 3]. Index 4 closes: pop 3, stack[0], length 4 - 0 = 4, somax_len = 4. - Index 5 is a closing parenthesis with nothing to match. Popping 0 empties the stack, so 5 becomes the base. The answer is 4, for the substring
()().
Code: Python, Java, C++
1class Solution:
2 def longestValidParentheses(self, s: str) -> int:
3 stack = [-1]
4 max_len = 0
5
6 for i, char in enumerate(s):
7 if char == '(':
8 stack.append(i)
9 else:
10 stack.pop()
11 if not stack:
12 stack.append(i)
13 else:
14 max_len = max(max_len, i - stack[-1])
15
16 return max_len1class Solution {
2 public int longestValidParentheses(String s) {
3 Stack<Integer> stack = new Stack<>();
4 stack.push(-1);
5 int maxLen = 0;
6
7 for (int i = 0; i < s.length(); i++) {
8 if (s.charAt(i) == '(') {
9 stack.push(i);
10 } else {
11 stack.pop();
12 if (stack.isEmpty()) {
13 stack.push(i);
14 } else {
15 maxLen = Math.max(maxLen, i - stack.peek());
16 }
17 }
18 }
19
20 return maxLen;
21 }
22}1class Solution {
2public:
3 int longestValidParentheses(string s) {
4 stack<int> stk;
5 stk.push(-1);
6 int maxLen = 0;
7
8 for (int i = 0; i < s.size(); i++) {
9 if (s[i] == '(') {
10 stk.push(i);
11 } else {
12 stk.pop();
13 if (stk.empty()) {
14 stk.push(i);
15 } else {
16 maxLen = max(maxLen, i - stk.top());
17 }
18 }
19 }
20
21 return maxLen;
22 }
23};Time and space complexity
O(n)
Each index is pushed and popped at most once during the single left-to-right scan.
O(n)
In the worst case, such as a string of only opening parentheses, every index sits on the stack.
Other approaches
Dynamic programming (time O(n), space O(n))
Let dp[i] be the length of the longest valid substring ending at i. A closing parenthesis after an opening one gives dp[i - 2] + 2, and one after another closing parenthesis checks the character before dp[i - 1] to extend a nested match.
Two counters, two passes (time O(n), space O(1))
Scan left to right counting opens and closes, recording a length when they are equal and resetting when closes exceed opens, then repeat right to left with the roles reversed. It uses constant space.
Common mistakes
- Pushing characters instead of indices makes it impossible to compute lengths.
- Forgetting the initial -1 makes a valid prefix like
()compute its length against an empty stack and crash or return 0. - Counting matched pairs over the whole string returns 4 for
()(()style inputs where the valid parts are not contiguous; lengths must come from positions. - Doing only the left-to-right counter pass misses cases like
((), which is why the counter method needs a second pass in the other direction.
Frequently asked questions
How does the stack solution for longest valid parentheses work?
The stack keeps indices of unmatched characters, with the last unmatched closing parenthesis (or -1) at the bottom. After each match, the current index minus the top of the stack is the length of the valid run ending here.
Why push -1 at the start?
It marks the position before the string, so a valid substring that begins at index 0 gets the correct length from i - (-1).
Can you solve it in O(1) space?
Yes. Two passes with open and close counters, one from each direction, find the longest balanced run without a stack.
Why is this a hard problem when valid parentheses is easy?
Checking a whole string only needs a balance count. Finding the longest valid substring requires knowing where each valid run starts, which is what the index stack or DP tracks. Nested and adjacent runs like (()()) also have to be merged correctly, which is easy to get wrong with ad hoc counting.