Search⌘ K
AI Features

Solution: Longest Valid Parentheses

Explore how to use the stack data structure to identify the longest valid substring of well-formed parentheses in a given string. Learn to track unmatched parentheses using an index-based stack, optimize with a single pass solution, and understand the time and space complexity of this algorithm in C++. This lesson helps you apply stack patterns to real coding interview problems involving matching parentheses.

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.

...