BackendML

Valid Parenthesis String

Medium3 min read
The Valid Parenthesis String problem requires determining whether a string containing parentheses and wildcard characters can be considered valid.

Problem

Given a string s containing only the characters (, ), and *, determine whether the string is valid.

The character * can be treated as an opening parenthesis (, a closing parenthesis ), or an empty string.

A valid parenthesis string must have every opening parenthesis matched with a closing parenthesis.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
s = "()"
Output
true

Example 2

Input
s = "(*)"
Output
true

Example 3

Input
s = "(*))"
Output
true

Solution

Approach 1: Stack

This solution uses two Stacks to track the positions of opening parentheses and wildcard characters. The open stack stores the indices of (, while the star stack stores the indices of *.

When we encounter ), we first try to match it with an opening parenthesis. If no opening parenthesis is available, we use * as an opening parenthesis. If neither is available, the string is invalid.

After processing the string, any remaining ( must be matched by a * that appears after it. Therefore, we compare their indices.
class Solution {
    public boolean checkValidString(String s) {
        Stack<Integer> open = new Stack<>();
        Stack<Integer> star = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '(') {
                open.push(i);
            } else if (c == '*') {
                star.push(i);
            } else {
                if (!open.isEmpty()) {
                    open.pop();
                } else if (!star.isEmpty()) {
                    star.pop();
                } else {
                    return false;
                }
            }
        }

        while (!open.isEmpty() && !star.isEmpty()) {
            if (open.pop() > star.pop()) {
                return false;
            }
        }
        return open.isEmpty();
    }
}

Approach 2: Greedy

This solution uses a Greedy approach by maintaining a range of possible unmatched opening parentheses. We use two variables: minOpen represents the minimum possible number of unmatched opening parentheses, while maxOpen represents the maximum possible number.

When we encounter (, both values increase because an opening parenthesis must be matched later. When we encounter ), both values decrease because it can close an opening parenthesis. For *, it can either be (, ), or empty, so minOpen decreases and maxOpen increases.

If maxOpen becomes negative, there are more closing parentheses than can possibly be matched. At the end, minOpen must be zero, meaning there is at least one valid interpretation of the string.
class Solution {
    public boolean checkValidString(String s) {
        int minOpen = 0;
        int maxOpen = 0;

        for (char c : s.toCharArray()) {
            if (c == '(') {
                minOpen++;
                maxOpen++;
            } else if (c == ')') {
                minOpen--;
                maxOpen--;
            } else {
                minOpen--;
                maxOpen++;
            }

            if (maxOpen < 0) {
                return false;
            }
            minOpen = Math.max(minOpen, 0);
        }
        return minOpen == 0;
    }
}

Complexity

For the Stack approach, each character is processed once, so the time complexity is O(n). The two stacks can store up to n indices, giving an extra space complexity of O(n).

For the Greedy approach, the string is traversed once, so the time complexity is O(n). Only two variables are used to track the possible range of unmatched opening parentheses, giving an extra space complexity of O(1).

Comments

No comments yet. Ask a question or share what helped.