Longest Valid Parentheses
JavaScript
hard
30 mins
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Examples
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 * 10^4
- s[i] is '(' or ')'
Function Signature
function longestValidParentheses(s) { // Your code here }
Test Cases
- Base cases: s = "" → 0, s = "(" → 0, s = ")" → 0
- Simple cases: s = "()" → 2, s = "(()" → 2, s = "())" → 2
- Medium cases: s = ")()())" → 4, s = "((()))" → 6
- Edge cases: s = "()()()" → 6, s = "(((((" → 0
- Complex cases: s = "(()())" → 6, s = "()(()" → 2
Notes
- Valid parentheses must be properly nested and balanced
- A substring is a contiguous sequence of characters
- Need to find the longest such substring
- Empty string returns 0
- Single characters are never valid
- Optimal solution uses stack with O(n) time complexity
Companies:
google
flipkart
amazon
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
