KatInterview

32. Longest Valid Parentheses

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Two-Pass Counter (O(1) Space)

This problem asks for the length of the longest valid parentheses substring. While standard stack-based or dynamic programming approaches work, there's a highly efficient and clever method using constant extra space.

Solution

Longest Valid Parentheses in Python

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        left, right, max_length = 0, 0, 0

        # First pass: Left to Right
        # This pass handles cases with extra ')' like ")()())"
        for char in s:
            if char == '(':
                left += 1
            else:
                right += 1
            
            if left == right:
                # Found a valid substring
                max_length = max(max_length, 2 * right)
            elif right > left:
                # This indicates an invalid sequence, so we reset counters.
                left, right = 0, 0

        # Reset counters for the second pass
        left, right = 0, 0

        # Second pass: Right to Left
        # This pass handles cases with extra '(' like "(()"
        for char in reversed(s):
            if char == '(':
                left += 1
            else:
                right += 1
            
            if left == right:
                # Found a valid substring
                max_length = max(max_length, 2 * left)
            elif left > right:
                # This indicates an invalid sequence from the right, so we reset.
                left, right = 0, 0
                
        return max_length

Longest Valid Parentheses in Java

class Solution {
    public int longestValidParentheses(String s) {
        int left = 0, right = 0, maxlength = 0;

        // First pass: Left to Right scan
        // This pass correctly finds the longest valid parentheses for strings
        // that are either valid or have excess open parentheses, but might fail
        // for strings with excess close parentheses at the beginning.
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                // When counts are equal, we have a validly formed substring.
                maxlength = Math.max(maxlength, 2 * right);
            } else if (right > left) {
                // If right > left, the sequence is invalid. Reset counters.
                left = 0;
                right = 0;
            }
        }

        // Reset counters for the second pass.
        left = 0;
        right = 0;

        // Second pass: Right to Left scan
        // This pass handles cases like "(()" which are missed by the first pass.
        // It is symmetric to the first pass.
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxlength = Math.max(maxlength, 2 * left);
            } else if (left > right) {
                // If left > right, the sequence is invalid from a right-to-left view.
                left = 0;
                right = 0;
            }
        }
        return maxlength;
    }
}

Longest Valid Parentheses in C++

class Solution {
public:
    int longestValidParentheses(string s) {
        int left = 0, right = 0, maxLength = 0;
        int n = s.length();

        // First pass: Left to Right
        // This pass handles cases with extra ')' like ")()())"
        for (int i = 0; i < n; i++) {
            if (s[i] == '(') {
                left++;
            } else {
                right++;
            }

            if (left == right) {
                // Found a valid substring
                maxLength = max(maxLength, 2 * right);
            } else if (right > left) {
                // This indicates an invalid sequence, so we reset counters.
                // For example, in "())", after the second ')', right becomes 2, left is 1.
                left = 0;
                right = 0;
            }
        }

        // Reset counters for the second pass
        left = 0;
        right = 0;

        // Second pass: Right to Left
        // This pass handles cases with extra '(' like "(()"
        for (int i = n - 1; i >= 0; i--) {
            if (s[i] == '(') {
                left++;
            } else {
                right++;
            }

            if (left == right) {
                // Found a valid substring
                maxLength = max(maxLength, 2 * left);
            } else if (left > right) {
                // This indicates an invalid sequence from the right, so we reset.
                // For example, in "(()", after the second '(', left becomes 2, right is 1.
                left = 0;
                right = 0;
            }
        }

        return maxLength;
    }
};

Longest Valid Parentheses in TypeScript

function longestValidParentheses(s: string): number {
    let left = 0, right = 0, maxLength = 0;

    // First pass: Left to Right scan
    // This pass correctly finds the longest valid parentheses for strings
    // that are either valid or have excess open parentheses, but might fail
    // for strings with excess close parentheses at the beginning.
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '(') {
            left++;
        } else {
            right++;
        }

        if (left === right) {
            // When counts are equal, we have a validly formed substring.
            maxLength = Math.max(maxLength, 2 * right);
        } else if (right > left) {
            // If right > left, the sequence is invalid. Reset counters.
            left = 0;
            right = 0;
        }
    }

    // Reset counters for the second pass.
    left = 0;
    right = 0;

    // Second pass: Right to Left scan
    // This pass handles cases like "(()" which are missed by the first pass.
    // It is symmetric to the first pass.
    for (let i = s.length - 1; i >= 0; i--) {
        if (s[i] === '(') {
            left++;
        } else {
            right++;
        }

        if (left === right) {
            maxLength = Math.max(maxLength, 2 * left);
        } else if (left > right) {
            // If left > right, the sequence is invalid from a right-to-left view.
            left = 0;
            right = 0;
        }
    }

    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.