Skip to main content
Back to problems
Leetcode
Medium
Strings
Stacks
Dynamic Programming
Longest Valid Parentheses

Find the length of the longest contiguous substring of balanced parentheses.

Acceptance 0%
Problem Statement

Given a string consisting only of the characters '(' and ')', determine the length of the longest contiguous substring that forms a valid parentheses sequence.

A parentheses substring is valid if it can be interpreted as a correctly matched sequence of opening and closing brackets.

Input Format

A single string s containing only '(' and ')' characters.

Output Format

Return one integer: the length of the longest valid contiguous parentheses substring.

Constraints

  • 0 <= s.length
  • s contains only '(' and ')'
  • If no valid substring exists, return 0
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "(()"

Output

2

Explanation

The longest valid contiguous substring is "()", which has length 2.

Example 2

Input

s = ")()())"

Output

4

Explanation

The longest valid contiguous substring is "()()", which has length 4.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.