Tutorialspoint
Problem
Solution
Submissions

Longest Valid Parentheses

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to find the length of the longest valid (well-formed) parentheses substring in a given string containing just the characters '(' and ')'. A valid parentheses string is one where every opening parenthesis '(' has a matching closing parenthesis ')' and they are properly nested.

Example 1
  • Input: s = "(()"
  • Output: 2
  • Explanation:
    • Step 1: Use a stack-based approach to track valid parentheses pairs.
    • Step 2: Process each character in the string, pushing indices of '(' onto the stack.
    • Step 3: When encountering ')', pop from stack and calculate the length of valid sequence.
    • Step 4: The longest valid parentheses substring is "()" with length 2.
Example 2
  • Input: s = ")()())"
  • Output: 4
  • Explanation:
    • Step 1: Use a stack-based approach to track valid parentheses pairs.
    • Step 2: Process each character in the string, pushing indices of '(' onto the stack.
    • Step 3: When encountering ')', pop from stack and calculate the length of valid sequence.
    • Step 4: The longest valid parentheses substring is "()()" with length 4.
Constraints
  • 0 ≤ s.length ≤ 3 * 10^4
  • s[i] is '(' or ')'
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n)
StackIBMDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using a stack to track opening parentheses
  • Another approach is using dynamic programming
  • You can also solve it with constant space using two passes
  • Track the current valid sequence length while scanning the string
  • Consider edge cases like empty strings or strings with only one type of parenthesis

Steps to solve by this approach:

 Step 1: Initialize a stack and push -1 as a base index.
 Step 2: Iterate through each character in the string.
 Step 3: If the current character is '(', push its index onto the stack.
 Step 4: If the current character is ')', pop the top element from the stack.
 Step 5: If the stack becomes empty after popping, push the current index as the new base.
 Step 6: If the stack is not empty, calculate the length of the valid substring (current index - top of stack).
 Step 7: Update the maximum length found so far.

Submitted Code :