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. Given a string containing just the characters '(' and ')', find the length of the longest valid parentheses substring.

Example 1
  • Input: s = "(()"
  • Output: 2
  • Explanation:
    • Step 1: The longest valid parentheses substring is "()".
    • Step 2: This substring has length 2.
    • Step 3: Therefore, the answer is 2.
Example 2
  • Input: s = ")()())"
  • Output: 4
  • Explanation:
    • Step 1: The longest valid parentheses substring is "()()".
    • Step 2: This substring has length 4.
    • Step 3: Therefore, the answer is 4.
Constraints
  • 0 ≤ strlen(s) ≤ 3 * 10^4
  • s[i] is '(' or ')'
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsStackKPMGSwiggy
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

  • Use a stack to keep track of indices of characters.
  • Push -1 initially to handle base case.
  • For each '(', push its index onto the stack.
  • For each ')', pop from stack and calculate current valid length.
  • Keep track of the maximum length found so far.
  • If stack becomes empty after popping, push current index.

Steps to solve by this approach:

 Step 1: Initialize a stack and push -1 as the base for calculating lengths.
 Step 2: Iterate through each character in the string.
 Step 3: If the character is '(', push its index onto the stack.
 Step 4: If the character is ')', pop from the stack.
 Step 5: If stack becomes empty after popping, push the current index as new base.
 Step 6: Otherwise, calculate the current valid length using current index minus top of stack.
 Step 7: Keep track of the maximum length encountered and return it.

Submitted Code :