Longest Valid Parentheses

Solution Code
class Solution:
    def longestValidParentheses(self, s: str) -> int:
        left = right = max_len = 0
        for char in s:
            if char == '(': left += 1
            else: right += 1
            if left == right: max_len = max(max_len, 2 * right)
            elif right > left: left = right = 0

Time Complexity

O(N)

Space Complexity

O(1)