• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
August 16, 2024 |2.3K Views

Length of the longest valid substring

Description
Discussion

Given a string consisting of opening and closing parenthesis, find the length of the longest valid parenthesis substring.

Examples:

Input : ((()
Output : 2
Explanation : ()

Input: )()())
Output : 4
Explanation: ()()

Input:  ()(()))))
Output: 6
Explanation:  ()(())


A Simple Approach is to find all the substrings of given string. For every string, check if it is a valid string or not. If valid and length is more than maximum length so far, then update maximum length. We can check whether a substring is valid or not in linear time using a stack (See this for details). Time complexity of this solution is O(n2)

 

An Efficient Solution can solve this problem in O(n) time. The idea is to store indexes of previous starting brackets in a stack. The first element of the stack is a special element that provides index before the beginning of valid substring (base for next valid string). 

 

Related Article : https://www.geeksforgeeks.org/length-of-the-longest-valid-substring/