Algo-Sim › Greedy

Valid Parenthesis String

Medium · Greedy · step through it in Java, Python and C++ on your own input

Decide if the stars can be read so the parentheses balance. Track the range [lo, hi] of open counts any reading could have, instead of every reading.

Problem

The string s holds '(', ')' and '*'. Each '*' may stand for '(', ')' or nothing. Return true if some choice for the stars makes s balanced: every ')' closes an earlier unmatched '(', and nothing is left open at the end.

Constraints

Edge cases to test

Follow-up questions

Why is a range enough?
Every count between lo and hi is reachable by some choice of stars, so tracking the interval replaces tracking every reading: O(n), O(1).
What is the DP alternative?
dp[i][open] over prefixes and open counts: O(n²) time. The range is that DP’s reachable set, which is always contiguous.

Solution

Java

public boolean checkValidString(String s) {
    int lo = 0, hi = 0;
    for (char ch : s.toCharArray()) {
        if (ch == '(') {
            lo++;
            hi++;
        } else if (ch == ')') {
            lo--;
            hi--;
        } else {
            lo--;
            hi++;
        }
        if (hi < 0) {
            return false;
        }
        lo = Math.max(lo, 0);
    }
    return lo == 0;
}

Python

def check_valid_string(s):
    lo = hi = 0
    for ch in s:
        if ch == "(":
            lo += 1
            hi += 1
        elif ch == ")":
            lo -= 1
            hi -= 1
        else:
            lo -= 1
            hi += 1
        if hi < 0:
            return False
        lo = max(lo, 0)
    return lo == 0

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool checkValidString(string &s) {
        int lo = 0, hi = 0;
        for (char ch : s) {
            if (ch == '(') {
                lo++;
                hi++;
            } else if (ch == ')') {
                lo--;
                hi--;
            } else {
                lo--;
                hi++;
            }
            if (hi < 0) {
                return false;
            }
            lo = std::max(lo, 0);
        }
        return lo == 0;
    }
};

More Greedy problems