Tutorialspoint
Problem
Solution
Submissions

Longest Valid Parentheses

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to find the length of the longest valid parentheses substring. A valid parentheses substring is a string of parentheses where every opening parenthesis '(' has a matching closing parenthesis ')' and they are correctly nested.

Example 1
  • Input: s = "(()"
  • Output: 2
  • Explanation: The last two characters "()" form a valid parentheses pair. The length of this valid substring is 2. Therefore, the longest valid parentheses substring has length 2.
Example 2
  • Input: s = ")()())"
  • Output: 4
  • Explanation: The first character ")" has no matching opening parenthesis, so it's invalid. The next four characters "()()" form a valid parentheses substring. The length of this valid substring is 4. Therefore, the longest valid parentheses substring has length 4.
Constraints
  • 0 <= s.length <= 3 * 10^4
  • s consists of only '(' and ')' characters
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n)
StringsStackDropboxD. E. Shaw
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 data structure to keep track of the indices of opening parentheses
  • Push -1 onto the stack initially as a base marker
  • Iterate through the string, if the current character is '(', push its index onto the stack
  • If the current character is ')', pop the top element from the stack
  • If the stack becomes empty, push the current index as a new base marker
  • If the stack is not empty, calculate the length of the current valid substring (current index - index at the top of the stack)
  • Update the maximum length found so far

Steps to solve by this approach:

 Step 1: Initialize a stack and push -1 as the base index to calculate substring lengths.

 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 from the stack.
 Step 5: If the stack becomes empty after popping, push the current index as a new base marker.
 Step 6: Otherwise, calculate the length of the current valid substring (current index - index at top of stack).
 Step 7: Return the maximum valid substring length found.

Submitted Code :