Longest Balanced Parentheses Substring

Quick Overview

Find the longest contiguous well-formed parentheses substring, including nested pairs, unmatched brackets, and empty input.

Longest Balanced Parentheses Substring

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem You receive a string `brackets` whose characters are all `(` or `)`. Return the greatest length of a contiguous substring that forms a well-formed parentheses sequence. A well-formed sequence pairs every opening parenthesis with a closing parenthesis in the correct nesting order. The characters you select must be adjacent in the original string; you cannot remove characters from the middle of a substring. Return `0` if the string contains no nonempty well-formed substring, including when `brackets` is empty. ### Examples **Example 1** ```text Input: brackets = ")((()))()(" Output: 8 ``` The substring `((()))()` is well formed and contains eight characters. Neither character just outside it can extend it into a longer well-formed substring. **Example 2** ```text Input: brackets = "(((" Output: 0 ``` There are no closing parentheses, so no nonempty substring is well formed. ### Constraints - `0 <= brackets.length <= 3 * 10^4` - Every character of `brackets` is `(` or `)`.

Overview: Find the longest contiguous well-formed parentheses substring, including nested pairs, unmatched brackets, and empty input.

Amazon logo
Amazon
Oct 18, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

You receive a string brackets whose characters are all ( or ). Return the greatest length of a contiguous substring that forms a well-formed parentheses sequence.

A well-formed sequence pairs every opening parenthesis with a closing parenthesis in the correct nesting order. The characters you select must be adjacent in the original string; you cannot remove characters from the middle of a substring.

Return 0 if the string contains no nonempty well-formed substring, including when brackets is empty.

Examples

Example 1

Input: brackets = ")((()))()("
Output: 8

The substring ((()))() is well formed and contains eight characters. Neither character just outside it can extend it into a longer well-formed substring.

Example 2

Input: brackets = "((("
Output: 0

There are no closing parentheses, so no nonempty substring is well formed.

Constraints

  • 0 <= brackets.length <= 3 * 10^4
  • Every character of brackets is ( or ) .