AlgoInsight

DSA problem

Longest Valid Parentheses

HardStacksPattern: Stackstop150AmazonGoogleMicrosoftMetaBloombergAdobe

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

The substring must be contiguous in s, and "valid" means a properly nested and matched sequence of parentheses (the same definition used by the standard Valid Parentheses problem, except over ( and ) only).

A brute-force solution checks every substring for validity, which is O(n^3). A dynamic-programming approach exists in O(n) time and O(n) space but requires careful case analysis on whether s[i] is ')' and what s[i - dp[i - 1] - 1] is.

The cleanest O(n) solution uses a stack of INDICES, seeded with -1 as a base. This sentinel represents the position just before any valid substring could start. Walk s from left to right: on '(' push the index. On ')', pop the top: if the stack is now empty, the popped index was the new "base" — push the current index as the new base. Otherwise, the current valid substring spans from the new top of the stack (exclusive) to the current index (inclusive), which has length i - stack.top(). Track the maximum such length across the scan. This is O(n) time and O(n) space.

Examples

Example 1
Input: s = "(()"
Output: 2
Explanation: The longest valid substring is "()", length 2.
Example 2
Input: s = ")()())"
Output: 4
Explanation: The longest valid substring is "()()", length 4.
Example 3
Input: s = ""
Output: 0
Explanation: Empty string has no valid substring.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackstringdynamic-programmingmatching

Browse all DSA problems