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 * 104s[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:
Imagine you have a long mixed-up string of left and right parentheses, and you want to find the longest unbroken sequence where every opening parenthesis is properly closed. The brute force approach works by inspecting every single possible slice or portion of the string, one by one, to see how long it is and whether it is completely balanced.
Here's how the algorithm would work step-by-step:
def longest_valid_parentheses(parentheses_string):
maximum_length = 0
# Iterate through every possible starting position to exhaustively check all slices
for start_index in range(len(parentheses_string)):
for end_index in range(start_index + 2, len(parentheses_string) + 1, 2):
current_slice = parentheses_string[start_index:end_index]
balance_count = 0
is_valid_slice = True
for character in current_slice:
if character == '(':
balance_count += 1
else:
balance_count -= 1
# Ensure closing parentheses never outnumber opening ones during the scan
if balance_count < 0:
is_valid_slice = False
break
# A valid slice must end with all opened parentheses properly closed
if is_valid_slice and balance_count == 0:
if len(current_slice) > maximum_length:
maximum_length = len(current_slice)
return maximum_lengthInstead of testing every possible grouping of parentheses, the optimal approach scans the sequence methodically to track how many valid matches we can form on the fly. By keeping a running tally and resetting when things don't match up, we can find the longest unbroken streak efficiently in a single pass.
Here's how the algorithm would work step-by-step:
def longest_valid_parentheses(parentheses_sequence):
max_valid_length = 0
open_count = 0
close_count = 0
for current_character in parentheses_sequence:
if current_character == '(':
open_count += 1
else:
close_count += 1
if open_count == close_count:
max_valid_length = max(max_valid_length, 2 * close_count)
# Reset counts when unmatched closing parenthesis breaks the valid sequence.
elif close_count > open_count:
open_count = 0
close_count = 0
open_count = 0
close_count = 0
for current_character in reversed(parentheses_sequence):
if current_character == ')':
close_count += 1
else:
open_count += 1
if open_count == close_count:
max_valid_length = max(max_valid_length, 2 * open_count)
# Reset counts when unmatched opening parenthesis breaks the backward sequence.
elif open_count > close_count:
open_count = 0
close_count = 0
# Combine insights from both scans to guarantee the absolute longest streak.
return max_valid_length| Case | How to Handle |
|---|---|
| Empty string or null input | Return zero immediately as no valid parentheses substring can exist. |
| String with a single character like '(' or ')' | Return zero because a single parenthesis cannot form a valid pair. |
| String with all opening brackets like '(((((' | The stack or dynamic programming approach will correctly calculate a maximum length of zero. |
| String with all closing brackets like ')))))' | Base pointers or stack resets ensure that unmatched closing brackets do not contribute to the length. |
| Valid parentheses starting with a closing bracket like ')(())' | The algorithm resets its tracking when encountering an unmatched closing bracket, correctly evaluating the trailing valid substring. |
| Interleaved or nested valid substrings like '()(())' | Using a stack of indices or a two-pass scan ensures that adjacent or nested valid parts merge correctly for the maximum length. |
| Maximum length constraints up to tens of thousands of characters | An optimal O(n) time and O(n) space linear scan ensures the solution scales efficiently without hitting time limits or stack overflows. |
| Extremely long strings causing integer overflow | Using standard integer types is safe since string lengths easily fit within typical 32-bit signed integer limits. |