101 Logo
onenoughtone

Problem Statement

Parentheses Validator

You are a software engineer working on a code editor that needs to validate nested parentheses in programming languages. The editor needs to identify the longest valid substring of parentheses to help users fix syntax errors.

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

A valid parentheses substring is one where every opening parenthesis '(' has a matching closing parenthesis ')', and they are properly nested.

Examples

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
Explanation: The input string is empty, so there are no valid parentheses.

Constraints

  • The input string consists of only '(' and ')'.
  • The length of the input string is between 0 and 3 × 10^4.
  • The solution should handle nested parentheses correctly.

Problem Breakdown

To solve this problem, we need to:

  1. A valid parentheses substring must have an equal number of opening and closing parentheses, and they must be properly nested.
  2. We can use a stack to keep track of the indices of unmatched parentheses.
  3. Dynamic programming can be used to build up the solution by considering one character at a time.
  4. We can also solve this problem using a two-pass approach with constant extra space.
ProblemSolutionCode
101 Logo
onenoughtone