KatInterview

678. Valid Parenthesis String

MediumSolutions 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

The problem requires us to validate a string composed of '(', ')', and ''. The character '' adds complexity as it can be treated as a '(', a ')', or an empty string. The core challenge lies in efficiently handling these multiple possibilities to determine if any combination results in a valid parenthesis string.

Solution

Valid Parenthesis String in Python

class Solution:
    def checkValidString(self, s: str) -> bool:
        min_open = 0  # Minimum possible open parentheses
        max_open = 0  # Maximum possible open parentheses

        for char in s:
            if char == '(':
                min_open += 1
                max_open += 1
            elif char == ')':
                min_open -= 1
                max_open -= 1
            else:  # char == '*'
                # '*' can act as ')', decreasing the minimum open count
                min_open -= 1
                # '*' can act as '(', increasing the maximum open count
                max_open += 1

            # If max_open becomes negative, it means we have an unmatched ')'
            # that cannot be balanced even if all previous '*' were '('.
            if max_open < 0:
                return False

            # We can't have a negative number of required open parentheses.
            # If min_open becomes negative, it means we might have an excess of ')'
            # that rely on '*' to be '('. However, '*' can also be empty.
            # So, we can reset min_open to 0.
            min_open = max(0, min_open)
        
        # After the loop, if min_open is 0, it means there's a path to a
        # valid string where all '(' are matched.
        # If min_open > 0, it means there are unmatched '(' that couldn't
        # be closed even if all remaining '*' were ')'.
        return min_open == 0

Valid Parenthesis String in Java

class Solution {
    public boolean checkValidString(String s) {
        int minOpen = 0; // Minimum number of open parentheses
        int maxOpen = 0; // Maximum number of open parentheses

        for (char c : s.toCharArray()) {
            if (c == '(') {
                minOpen++;
                maxOpen++;
            } else if (c == ')') {
                minOpen--;
                maxOpen--;
            } else { // c == '*'
                // If '*' is treated as ')', minOpen decreases
                minOpen--;
                // If '*' is treated as '(', maxOpen increases
                maxOpen++;
            }

            // If maxOpen is negative, it means there are too many ')'
            // even if all '*' are treated as '('. The string is invalid.
            if (maxOpen < 0) {
                return false;
            }

            // minOpen should not be negative. A negative minOpen means we have
            // an excess of ')' that could be matched by previous '*'s.
            // Since '*' can also be empty, we are not forced to match them.
            // So we can clamp minOpen at 0.
            minOpen = Math.max(0, minOpen);
        }

        // For the string to be valid, the number of open parentheses must be exactly 0.
        // Our range of possible open parentheses counts is [minOpen, maxOpen].
        // If minOpen is 0, it means a balance of 0 is possible.
        // If minOpen > 0, we have unmatched open parentheses.
        return minOpen == 0;
    }
}

Valid Parenthesis String in C++

class Solution {
public:
    bool checkValidString(string s) {
        int min_open = 0; // Represents the minimum number of open parentheses needed
        int max_open = 0; // Represents the maximum number of open parentheses possible

        for (char c : s) {
            if (c == '(') {
                min_open++;
                max_open++;
            } else if (c == ')') {
                min_open--;
                max_open--;
            } else { // c == '*'
                // '*' can be ')' which decreases the count of open parentheses
                min_open--; 
                // '*' can be '(' which increases the count of open parentheses
                max_open++; 
            }

            // If max_open becomes negative, it means we have too many ')'
            // even if all '*' were treated as '('. This is an invalid state.
            if (max_open < 0) {
                return false;
            }

            // min_open can't be negative. If it is, it means we might have an excess
            // of ')' that could be matched by '*'s. However, '*' can also be
            // an empty string, so we are not forced to have a negative balance.
            // We can reset it to 0.
            min_open = max(0, min_open);
        }

        // After iterating through the string, for it to be valid,
        // we must be able to achieve a balance of 0.
        // The range of possible balances is [min_open, max_open].
        // If min_open is 0, it means a balance of 0 is achievable.
        // If min_open > 0, it means we have a surplus of '(' that cannot be matched.
        return min_open == 0;
    }
};

Valid Parenthesis String in TypeScript

function checkValidString(s: string): boolean {
    let minOpen: number = 0; // Minimum possible open parentheses
    let maxOpen: number = 0; // Maximum possible open parentheses

    for (const char of s) {
        if (char === '(') {
            minOpen++;
            maxOpen++;
        } else if (char === ')') {
            minOpen--;
            maxOpen--;
        } else { // char === '*'
            // '*' can act as ')', decreasing the minimum open count
            minOpen--;
            // '*' can act as '(', increasing the maximum open count
            maxOpen++;
        }

        // If max_open becomes negative, it means we have an unmatched ')'
        // that cannot be balanced even if all previous '*' were '('.
        if (maxOpen < 0) {
            return false;
        }

        // We can't have a negative number of required open parentheses.
        // If min_open becomes negative, it means we might have an excess of ')'
        // that rely on '*' to be '('. However, '*' can also be empty.
        // So, we can reset min_open to 0.
        minOpen = Math.max(0, minOpen);
    }

    // After the loop, if min_open is 0, it means there's a path to a
    // valid string where all '(' are matched.
    // If min_open > 0, it means there are unmatched '(' that couldn't
    // be closed even if all remaining '*' were ')'.
    return minOpen === 0;
};

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.