Valid Parenthesis String

Medium Stack Stack Basics

Valid Parenthesis String is a medium stack problem solved with the stack basics pattern. The best approach, optimal (greedy range of open counts), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion with memo (position, open count) up.

Problem

You are given a string s made only of the characters '(', ')' and '*'. Each star is a wildcard: you may treat it as '(', as ')', or as if it were not there at all, and every star can be chosen independently.

Return true if some choice for the stars turns s into a balanced bracket string, and false otherwise. A string is balanced when every '(' is closed by a later ')', every ')' closes an earlier '(', and the pairs nest properly. The empty string counts as balanced.

Examples

Example 1

Input
s = "((*)"
Output
true
Why
Let the star act as a closing bracket: "(())" is balanced.

Example 2

Input
s = "*)("
Output
false
Why
The last character is an opening bracket with nothing after it to close it, whatever the star becomes.

Example 3

Input
s = "(*)))"
Output
false
Why
There are three closing brackets but at most two characters (the bracket and the star) can open, so some ')' is always unmatched.

Constraints

  • 1 <= s.length <= 100
  • Every character of s is '(', ')' or '*'.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 57 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Recursion with memo (position, open count)O(n²)O(n²)
Two stacks of indexesO(n)O(n)
Optimal (greedy range of open counts)O(n)O(1)

1Recursion with memo (position, open count)

TimeO(n²)There are at most (n + 1)² states (index, open), and each does constant work besides its three cached calls.
SpaceO(n²)The memo table has (n + 1)² entries; the recursion is at most n deep.

Walk the string while remembering how many brackets are open. A '(' adds one, a ')' removes one, and a star tries all three choices. The state is just (index, open), so caching it keeps the search polynomial.

  1. can(i, open) answers: can s[i..] be finished when open brackets are currently unclosed?
  2. If open < 0, a ')' had nothing to match: false. At the end of the string, the answer is open == 0.
  3. If more brackets are open than characters remain, it cannot recover: false.
  4. '(' → can(i + 1, open + 1); ')' → can(i + 1, open - 1); '*' → any of the three.
  5. Store each answer in memo[i][open] before returning it.
class Solution {
    private Boolean[][] memo;
    private String s;

    public boolean checkValidString(String s) {
        this.s = s;
        memo = new Boolean[s.length() + 1][s.length() + 2];
        return can(0, 0);
    }

    private boolean can(int i, int open) {
        if (open < 0) return false;
        if (i == s.length()) return open == 0;
        if (open > s.length() - i) return false;
        if (memo[i][open] != null) return memo[i][open];
        char c = s.charAt(i);
        boolean ok;
        if (c == '(') ok = can(i + 1, open + 1);
        else if (c == ')') ok = can(i + 1, open - 1);
        else ok = can(i + 1, open + 1) || can(i + 1, open - 1) || can(i + 1, open);
        memo[i][open] = ok;
        return ok;
    }
}

2Two stacks of indexes

TimeO(n)Every index is pushed once and popped at most once.
SpaceO(n)The two stacks together hold at most n indexes.

Keep the positions of unmatched '(' on one stack and of stars on another. A ')' prefers to close a real '(' and falls back to a star. At the end, every leftover '(' needs a star that comes after it.

  1. Push the index of every '(' onto open and of every '*' onto star.
  2. On ')': pop open if it is not empty, otherwise pop star; if both are empty, return false.
  3. After the scan, while both stacks are non-empty: if the top '(' sits after the top star, that star cannot close it, so return false; otherwise pop both.
  4. Return true exactly when open is empty (leftover stars just become empty).
class Solution {
    public boolean checkValidString(String s) {
        Deque<Integer> open = new ArrayDeque<>();
        Deque<Integer> star = new ArrayDeque<>();
        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();
    }
}

3Optimal (greedy range of open counts)

TimeO(n)One pass, constant work per character.
SpaceO(1)Only the two counters lo and hi.

After each prefix, the number of unclosed brackets could be any value in a range [lo, hi]: hi assumes every star opened, lo assumes every star closed. If even hi goes negative, too many ')' have appeared. A count below zero is never a real option, so lo is clamped at zero. At the end, zero must be reachable, which means lo == 0.

  1. Start with lo = hi = 0.
  2. '(' → lo++, hi++. ')' → lo--, hi--. '*' → lo-- (star closes), hi++ (star opens).
  3. If hi < 0, return false: no choice of stars can cover this many ')'.
  4. Set lo = max(lo, 0), dropping the impossible negative counts.
  5. After the scan, return lo == 0.
class Solution {
    public boolean checkValidString(String s) {
        int lo = 0, hi = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                lo++;
                hi++;
            } else if (c == ')') {
                lo--;
                hi--;
            } else {
                lo--;
                hi++;
            }
            if (hi < 0) return false;
            lo = Math.max(lo, 0);
        }
        return lo == 0;
    }
}

Edge cases to test

  • A single star (valid: it becomes empty)
  • A single bracket of either kind (invalid)
  • Only stars (always valid)
  • A star that appears after an unmatched '(' can close it, but one that appears before it cannot
  • More ')' than '(' plus '*' (invalid at the first such point)

Hints

Hint 1

Without stars, a counter of open brackets is enough: it must never go below zero and must end at zero.

Hint 2

With stars the counter is no longer one number. Which values can it take after each character?

Hint 3

The possible open counts after each prefix form a whole range [lo, hi]. Track only its two ends, never let lo go below zero, and fail if hi drops below zero.

FAQ

What is the best time complexity for Valid Parenthesis String?

Optimal (greedy range of open counts) runs in O(n) time and O(1) extra space. One pass, constant work per character.

Which pattern does Valid Parenthesis String use?

It is a stack problem that uses the stack basics pattern. Other problems with the same pattern: Valid Parentheses, Baseball Game, Asteroid Collision.

Is there a brute force solution for Valid Parenthesis String?

Yes. Recursion with memo (position, open count) takes O(n²) time and O(n²) space. Walk the string while remembering how many brackets are open.

Which edge cases should I test for Valid Parenthesis String?

A single star (valid: it becomes empty); A single bracket of either kind (invalid); Only stars (always valid); A star that appears after an unmatched '(' can close it, but one that appears before it cannot; More ')' than '(' plus '' (invalid at the first such point).