Search⌘ K
AI Features

Solution: Longest Valid Parentheses

Explore how to solve the Longest Valid Parentheses problem using a stack-based algorithm. Learn to track indices of parentheses for matching pairs and calculate the maximum length of valid substrings efficiently. This lesson clarifies the stack pattern's role in handling nested structures and helps you implement an optimal O(n) time and space 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.

...