32. Longest Valid Parentheses
Asked at 25Meta55Amazon51Microsoft49Bloomberg47Google42Visa61Nike100Nykaa100Roku87Zoho78MAQ Software69MakeMyTrip65InMobi62Sprinklr54Morgan Stanley54Booking.com50IBM50TikTok50DE Shaw47Snap45Accenture44LinkedIn37Oracle35Infosys30Uber30
Problem
s contains only ( and ). Return the length of its longest valid (well-formed) parentheses substring.
Example: "(()" → 2; ")()())" → 4
Constraints: length ≤ 3·10⁴.
Stack of indices, seeded with -1 as the "last invalid position". ( → push index. ) → pop; if the stack is empty, push this index as the new base; else the valid run length is i − stack[-1].
s = ) ( ) ( ) )
i 0 1 2 3 4 5
i=0 ')' pop -1 -> empty -> push 0
i=2 ')' pop 1 -> len 2-0 = 2
i=4 ')' pop 3 -> len 4-0 = 4 <- best
Complexity: O(n).
class Solution:
def longestValidParentheses(self, s: str) -> int:
st, best = [-1], 0
for i, ch in enumerate(s):
if ch == "(":
st.append(i)
else:
st.pop()
if not st:
st.append(i)
else:
best = max(best, i - st[-1])
return best
assert Solution().longestValidParentheses("(()") == 2
assert Solution().longestValidParentheses(")()())") == 4
assert Solution().longestValidParentheses("") == 0
class Solution {
public int longestValidParentheses(String s) {
Deque<Integer> st = new ArrayDeque<>();
st.push(-1);
int best = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') st.push(i);
else {
st.pop();
if (st.isEmpty()) st.push(i);
else best = Math.max(best, i - st.peek());
}
}
return best;
}
}
func longestValidParentheses(s string) int {
st, best := []int{-1}, 0 // stack bottom = index just before the current valid run
for i := 0; i < len(s); i++ {
if s[i] == '(' {
st = append(st, i)
continue
}
st = st[:len(st)-1]
if len(st) == 0 {
st = append(st, i) // unmatched ')': new base
} else {
best = max(best, i-st[len(st)-1])
}
}
return best
}