Skip to main content

Longest Valid Parentheses

LeetCode 32 | Difficulty: Hard​

Hard

Problem Description​

Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses **substring.

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

Constraints:

- `0 <= s.length <= 3 * 10^4`

- `s[i]` is `'('`, or `')'`.

Topics: String, Dynamic Programming, Stack


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

Stack​

Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.

When to use

Matching brackets, next greater element, evaluating expressions, backtracking history.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 72 ms)​

MetricValue
Runtime72 ms
Memory23.2 MB
Date2020-01-12
Solution
public class Solution {
public int LongestValidParentheses(string s) {
Stack<int> stack = new Stack<int>();
int result = 0;
for (int i = 0; i < s.Length; i++)
{
if(s[i] == '(')
{
stack.Push(i);
}
else if(stack.Count >0 && s[stack.Peek()] == '(')
{
stack.Pop();
int validLen = stack.Count == 0 ? i+1 : i- stack.Peek();
result = Math.Max(result, validLen);
}
else
{
stack.Push(i);
}
}

return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Dynamic Programming$O(n)$$O(n)$
Stack$O(n)$$O(n)$

Interview Tips​

Key Points
  • Break the problem into smaller subproblems. Communicate your approach before coding.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.
  • Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?