Search⌘ K
AI Features

Solution: Longest Valid Parentheses

Understand how to apply the stack pattern to identify the longest well-formed parentheses substring in a given string. Learn to use indices in a stack to track unmatched parentheses, calculate valid substring lengths, and achieve an optimal O(n) time solution.

Statement

You are given a string composed entirely of ‘(’ and ‘)’ characters. Your goal is to identify the longest contiguous segment (substring) within this string that represents a “well-formed” or “valid” sequence of parentheses.

A substring is considered valid if:

  1. Every opening parenthesis ‘(’ has a corresponding closing parenthesis ‘)’.

  2. The pairs of parentheses are correctly nested.

Return the length of this longest valid substring.

Constraints:

  • 00 \leq s.length 3×103\leq 3 ...