Search⌘ K
AI Features

Solution: Longest Valid Parentheses

Explore how to identify the longest contiguous well-formed parentheses substring by applying the stack pattern. Understand the stack's role in matching parentheses pairs, implement the algorithm to track indexes efficiently, and analyze time and space complexity. This lesson equips you with techniques useful for solving related string problems in coding interviews.

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.

...