Longest Valid Parentheses - Problem
The Challenge: You're given a string containing only parentheses characters
What makes parentheses valid?
โข Every opening parenthesis
โข They must be in the correct order (no closing before its matching opening)
Example: In the string
'(' and ')'. Your task is to find the length of the longest contiguous substring that forms valid (well-formed) parentheses.What makes parentheses valid?
โข Every opening parenthesis
'(' must have a corresponding closing parenthesis ')'โข They must be in the correct order (no closing before its matching opening)
Example: In the string
"(()", the longest valid parentheses substring is "()" with length 2.
Goal: Return the length of the longest valid parentheses substring, not the substring itself. Input & Output
example_1.py โ Basic Valid Parentheses
$
Input:
s = "(()"
# String with one valid pair
โบ
Output:
2
๐ก Note:
The longest valid parentheses substring is "()" which has length 2. The first '(' cannot be matched.
example_2.py โ Multiple Valid Pairs
$
Input:
s = ")()())"
# String with consecutive valid pairs
โบ
Output:
4
๐ก Note:
The longest valid parentheses substring is "()()" which has length 4. The first and last characters cannot form valid pairs.
example_3.py โ Empty String Edge Case
$
Input:
s = ""
# Empty string
โบ
Output:
0
๐ก Note:
Empty string contains no parentheses, so the longest valid parentheses substring has length 0.
Constraints
- 0 โค s.length โค 3 ร 104
- s[i] is either '(' or ')'
- String contains only parentheses characters
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
Valid parentheses form nested or sequential patterns where every '(' has a matching ')' after it
2
Track with Stack
Use a stack to remember positions of unmatched '(' characters and calculate lengths when we find matches
3
Calculate Lengths
When we find a ')', match it with the most recent '(' and calculate the length of the valid sequence
4
Handle Edge Cases
Manage cases where ')' appears without matching '(' by updating our base position for calculations
Key Takeaway
๐ฏ Key Insight: The stack-based approach efficiently tracks unmatched parentheses positions, allowing us to calculate the length of valid sequences in O(n) time by leveraging the stack's top element as a reference point for distance calculations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code