Hone logo
Hone
Problems

Longest Valid Parentheses

Given a string containing only opening and closing parentheses, determine the length of the longest valid (well-formed) parentheses substring. This is a common problem in computer science that tests your understanding of string manipulation and data structures, often solved using stacks or dynamic programming.

Problem Description

Your task is to find the length of the longest contiguous substring within a given input string that represents a sequence of well-formed parentheses. A well-formed parentheses sequence is one where every opening parenthesis has a corresponding closing parenthesis, and they are properly nested.

Key Requirements:

  • Identify all valid parentheses substrings.
  • Return the length of the longest such substring.
  • If no valid parentheses substring exists, the length should be 0.

Expected Behavior:

  • The function should accept a string s consisting only of '(' and ')' characters.
  • The function should return a non-negative integer representing the length of the longest valid parentheses substring.

Edge Cases to Consider:

  • An empty input string.
  • A string with only opening parentheses.
  • A string with only closing parentheses.
  • A string with interleaved but invalid parentheses sequences.
  • A string with a single valid pair "()".

Examples

Example 1:

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

Example 2:

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

Example 3:

Input: s = ""
Output: 0
Explanation: An empty string has no valid parentheses substrings.

Example 4:

Input: s = "()(()"
Output: 2
Explanation: The valid substrings are "()" (length 2) and "()" (length 2). The longest is 2.

Example 5:

Input: s = "(()())"
Output: 6
Explanation: The entire string "(()())" is a valid parentheses substring.

Constraints

  • 0 <= length(s) <= 3 * 10^4
  • s contains only the characters '(' and ')'.

Notes

Consider how you can efficiently track unmatched parentheses. A stack data structure is a common approach to solve this problem. You might also explore dynamic programming solutions. Think about how to identify the start and end of valid substrings.

Loading editor...
plaintext