Search⌘ K
AI Features

Solution: Longest Valid Parentheses

Learn to identify the longest well-formed parentheses substring by implementing a stack-based algorithm. This lesson covers using stack operations to track unmatched parentheses indexes, calculate valid substring lengths, and optimize time and space complexity. Gain practical skills for coding interview problems involving nested structures.

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.

...