Given a string containing just the characters '('
and ')'
, return the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = "" Output: 0
Constraints:
0 <= s.length <= 3 * 104
s[i]
is '('
, or ')'
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force way to find the longest valid parentheses sequence is to check every possible sequence of parentheses within the string. We're basically trying every starting point and every possible length to see if that section of the parentheses string is 'valid'. By checking every possible substring, we are guaranteed to find the longest valid one.
Here's how the algorithm would work step-by-step:
def longest_valid_parentheses_brute_force(parentheses_string):
max_length = 0
# Consider all possible substrings
for start_index in range(len(parentheses_string)):
for end_index in range(start_index, len(parentheses_string)):
substring = parentheses_string[start_index:end_index + 1]
# Check if the current substring is valid
if is_valid_parentheses(substring):
max_length = max(max_length, len(substring))
return max_length
def is_valid_parentheses(substring):
stack = []
# Iterate through each character in the substring
for character in substring:
if character == '(':
stack.append(character)
elif character == ')':
# If the stack is empty, then it is invalid
if not stack:
return False
stack.pop()
# A valid string means all open parentheses have been closed
return not stack
The efficient way to find the longest valid set of parentheses is to scan the input twice, once from left to right and once from right to left. We use counters to keep track of open and closed parentheses and reset these counters when they become unbalanced.
Here's how the algorithm would work step-by-step:
def longest_valid_parentheses(s):
max_length = 0
open_parentheses_count = 0
closed_parentheses_count = 0
# Scan from left to right.
for character in s:
if character == '(':
open_parentheses_count += 1
else:
closed_parentheses_count += 1
if open_parentheses_count == closed_parentheses_count:
max_length = max(max_length, 2 * open_parentheses_count)
elif closed_parentheses_count > open_parentheses_count:
# Reset counts when unbalanced.
open_parentheses_count = 0
closed_parentheses_count = 0
open_parentheses_count = 0
closed_parentheses_count = 0
# Scan from right to left.
for character in reversed(s):
if character == '(':
open_parentheses_count += 1
else:
closed_parentheses_count += 1
if open_parentheses_count == closed_parentheses_count:
max_length = max(max_length, 2 * open_parentheses_count)
elif open_parentheses_count > closed_parentheses_count:
# Reset counts when unbalanced.
open_parentheses_count = 0
closed_parentheses_count = 0
return max_length
Case | How to Handle |
---|---|
Empty string input | Return 0 as there are no parentheses to validate. |
String with only one character | Return 0 as a single parenthesis is never valid. |
String with only open parentheses '(((' | Return 0 as there are no closing parentheses to form a valid substring. |
String with only closed parentheses ')))' | Return 0 as there are no open parentheses to form a valid substring. |
String with a perfectly balanced parentheses '()()' | The algorithm should correctly identify and return the total length of the string. |
String with nested and balanced parentheses '(()())' | The algorithm should correctly identify and return the total length of the string. |
String with unbalanced parentheses at the beginning ')(()))' | The algorithm should identify the longest valid substring, '()))', and return its length, which is 4. |
Maximum string length allowed by the platform with complex unbalanced structure | Ensure the solution has O(n) time complexity using dynamic programming or stack to avoid exceeding time limit or memory limit. |