15% off all plans & roadmaps Use code

See plans

Valid Parenthesis String

Updated

TL;DR: Decide whether the wildcards in a string of `(`, `)` and `*` can be set so the parentheses balance. Track the lowest and highest possible count of open parentheses in one pass.

Problem

You are given a string s made of three kinds of characters: (, ) and *. Decide whether it can be read as a correctly balanced parenthesis sequence.

Each * can be treated as a single (, a single ), or an empty string. Every other character keeps its normal meaning. Return true if some choice for every * gives a valid sequence, and false otherwise.

A valid sequence has every ( matched by a later ), and no ) appears before the ( it closes.

Example 1

Input: s = "(*()"
Output: true
Explanation: Treat the * as ) to get (()), which is balanced.

Example 2

Input: s = "())*"
Output: false
Explanation: The first three characters already contain one unmatched ), and the final * comes too late to fix that.

Example 3

Input: s = "***"
Output: true
Explanation: Treat the wildcards as (, ) and empty to get ().

Constraints

  • 1 <= s.length <= 10^5
  • Each character of s is (, ) or *.

Constraints that matter

  • n up to 10^5 rules out trying every interpretation. With k wildcards there are 3^k of them, so the search must be summarised, not enumerated.
  • n up to 10^5 also rules out an O(n^2) table of (index, balance) states if you want a safe margin. A linear scan is the target.
  • The alphabet has only three characters, so the whole state of a prefix is one number: how many ( are still open. Wildcards make that number uncertain, not complicated.
  • Only the count of open parentheses matters, not which ones. That is why two integers or two stacks of indices are enough.

View on LeetCode

Hints

Hint 1

This is a valid parentheses matching problem.

Hint 2

Try every reading of every star.

Solution

Intuition

This is a valid parentheses matching problem. In a plain string you scan left to right and keep one number: the count of unmatched (. It must never drop below zero, and it must be zero at the end.

Picture a needle that can rest anywhere between two stops on a dial. The low stop is every star acting as a closing bracket, and the high stop is every star acting as an opening bracket.

A * breaks the single number, because it can add one, subtract one, or change nothing. After a few stars you hold many possible counts at once. The reachable counts form a contiguous range. If a count of 3 and a count of 1 are both reachable, then 2 is reachable too, since you can turn one more star into an empty character.

A contiguous range needs only two numbers: the lowest reachable count and the highest. The highest count assumes every star is (. The lowest assumes every star is ), but never goes below zero, because a count below zero means a ) had nothing to close and that branch is dead.

Two checks finish the job. If the highest count goes below zero, even the best reading has too many ), so you stop with false. At the end, the string works if zero is in the range, and since the lowest count is clamped at zero, that means the lowest count equals zero.

The same idea has a stack version. Keep the indices of unmatched ( in one stack and the indices of stars in another. A ) consumes a ( if one exists, otherwise a star. Leftover ( need a star that appears after them.

Watch the pattern animation

Worked example

Input: s = "(*()"
Output: true
Explanation: The * at index 1 can act as ). The string then reads (()), where the first ( closes with the ) from the star and the second ( closes with the final ).

Approach 1: Brute force recursion

Try every reading of every star. Walk the string with a running balance of open parentheses. For ( add one, for ) subtract one, and for * branch into three calls: empty, ) and (.

A branch dies as soon as the balance goes below zero. A branch succeeds if it reaches the end with balance zero. With k stars there can be 3^k branches, so this is correct but exponential.

Memoising on the pair (index, balance) cuts the work to O(n^2) states, since the balance never exceeds n. That is still too much for n = 10^5, and it hides a simpler fact: the reachable balances form a range.

Steps

  1. Define dfs(i, bal) as: can the suffix starting at i finish with balance zero, given the current balance bal.
  2. If bal < 0, return false, because a ) has no partner.
  3. If i is the string length, return whether bal == 0.
  4. For (, recurse with bal + 1. For ), recurse with bal - 1.
  5. For *, return true if any of the three calls succeeds: bal, bal - 1, bal + 1.
  6. Start with dfs(0, 0).

Dry run

On (*() the call tree is small.

  • dfs(0,0): ( leads to dfs(1,1).
  • dfs(1,1) is the star. Try empty first: dfs(2,1). The ( gives dfs(3,2), the ) gives dfs(4,1). The end is reached with balance 1, so false.
  • Back at the star, try ): dfs(2,0). The ( gives dfs(3,1), the ) gives dfs(4,0). The end is reached with balance 0, so true.

The star branch returns true, so the answer is true. Two of the three star choices were explored before success.

Complexity

TimeO(3^k) where k is the number of stars
SpaceO(n) recursion depth

Let n be the string length and k the number of stars. Each star starts up to three calls, and every other character starts one, so the call tree has at most 3^k leaves. Each call does O(1) work, giving O(3^k) time up to a factor of n for the path length. The recursion goes one level per character, so the stack depth is n, which is O(n) space.

PythonTested in our runner

from typing import List, Optional
from functools import lru_cache
import sys

class Solution:
    def checkValidString(self, s: str) -> bool:
        n = len(s)
        # suffix count of parens left to bound the balance
        sys.setrecursionlimit(max(10000, 4 * n + 100))
        # remaining[i] = number of chars from i to end; balance above that can never close
        memo = set()

        def dfs(i: int, bal: int) -> bool:
            if bal < 0 or bal > n - i:
                return False
            if i == n:
                return bal == 0
            if (i, bal) in memo:
                return False  # already explored and failed
            c = s[i]
            if c == '(':
                res = dfs(i + 1, bal + 1)
            elif c == ')':
                res = dfs(i + 1, bal - 1)
            else:
                # star: empty, close, or open
                res = dfs(i + 1, bal) or dfs(i + 1, bal - 1) or dfs(i + 1, bal + 1)
            if not res:
                memo.add((i, bal))
            return res

        return dfs(0, 0)
Valid Parentheses Matching pattern infographic for Valid Parenthesis String

Solution pattern

Valid Parentheses Matching

Part of Stack Patterns

Approach 2: Two stacks of indicesValid Parentheses Matching

What's slow: the recursion explores each star three ways and revisits the same balances again and again. The balance is only a count, so the exact choice for each star is rarely needed.

The insight that fixes it: decide star roles lazily, using positions. Keep one stack of indices of unmatched ( and one of indices of stars. A ) should close a real ( first, because stars are flexible and worth saving. If no ( is open, the ) borrows a star. If neither exists, the string is dead.

After the scan, some ( may be left over. Each needs a star to its right, because that star must act as ) and a ) must come after its (. Match the leftover ( and stars from the top of the stacks, and check the order.

Steps

  1. Create two empty stacks, open and star, holding indices.
  2. Scan left to right. Push i onto open for ( and onto star for *.
  3. On ), pop from open if it is not empty.
  4. Otherwise pop from star if it is not empty.
  5. Otherwise return false, because nothing can close this ).
  6. After the scan, while both stacks are non-empty, pop one index from each. If the ( index is greater than the star index, return false.
  7. Return true only if open is empty.

Dry run

Trace (*().

  • i=0 (: open = [0].
  • i=1 *: star = [1].
  • i=2 (: open = [0, 2].
  • i=3 ): open is not empty, so pop 2. Now open = [0].
  • Scan ends with open = [0] and star = [1]. Pop both: the ( at 0 is before the star at 1, so the star can close it.
  • open is empty, so the answer is true.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. Each index is pushed at most once and popped at most once, and the final matching loop pops each stack entry at most once. That is O(n) total work. In the worst case, such as (((( or ****, one stack holds about n indices, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def checkValidString(self, s: str) -> bool:
        open_stack = []
        star_stack = []

        for i, c in enumerate(s):
            if c == '(':
                open_stack.append(i)
            elif c == '*':
                star_stack.append(i)
            else:
                if open_stack:
                    open_stack.pop()
                elif star_stack:
                    star_stack.pop()
                else:
                    return False

        # each leftover '(' needs a star to its right
        while open_stack and star_stack:
            if open_stack.pop() > star_stack.pop():
                return False

        return not open_stack

Approach 3: Greedy range of open countsOptimal

What's slow: the two-stack version stores indices, but the answer depends only on how many ( can be open, not where they are. That costs O(n) space and a second pass for no gain.

The insight that fixes it: keep the lowest and highest possible open counts, low and high. A ( raises both. A ) lowers both.

A * lowers low (star as )) and raises high (star as (), and the unchanged choice sits between them. Clamp low at zero, because a negative count is not a real state. If high drops below zero, return false. At the end, accept when low == 0.

Steps

  1. Set low = 0 and high = 0.
  2. For (: increment low and high.
  3. For ): decrement high, and set low = max(0, low - 1).
  4. For *: increment high, and set low = max(0, low - 1).
  5. After each character, if high < 0, return false.
  6. After the loop, return low == 0.

Dry run

Trace (*() and watch the range [low, high].

StepCharlowhighNote
start00only count 0 is possible
1(11both bounds rise
2*02low falls to 0 (star as )), high rises to 2 (star as ()
3(13both bounds rise
4)02both fall, low stays at or above 0
end02low == 0, so return true

Zero is inside the final range, so some reading of the star balances the string. High never went negative.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of s. The loop visits each character once and does a constant number of comparisons and additions, so time is O(n). The only state is the two integers low and high, so space is O(1). Both values stay between 0 and n in magnitude, so they fit in a 32-bit int.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def checkValidString(self, s: str) -> bool:
        low = 0   # fewest open '(' possible
        high = 0  # most open '(' possible

        for c in s:
            if c == '(':
                low += 1
                high += 1
            elif c == ')':
                low = max(0, low - 1)
                high -= 1
            else:
                low = max(0, low - 1)
                high += 1

            if high < 0:  # too many ')' even in the best reading
                return False

        return low == 0

Common mistakes

  • Forgetting the clamp, writing low -= 1 on ) and *. Then low can go negative, and inputs like )* can end with a false reading. Use low = max(0, low - 1).
  • Checking low < 0 instead of high < 0 for the early exit. low is clamped and never negative. The dead-prefix signal is high < 0, so test that after every character.
  • Returning high == 0 or low == high at the end. The string is valid if zero is anywhere in the range, and since low is clamped, that means low == 0. Return low == 0.
  • Treating * as only one fixed choice, for example always ) when the balance is positive. That greedy rule fails on (*)(-style cases where a later ( needs the star. Track the full range, or use the two-stack check with index order.
  • In the two-stack version, popping a star before a ( on ). Stars are flexible and should be saved. Pop open first, then fall back to star.
  • In the two-stack version, matching leftover ( and stars without comparing indices, as in *(. The star comes before the (, so it cannot close it. Compare open.pop() > star.pop() and return false when the ( is later.

Edge cases

  • * alone: the star can be empty, so the answer is true. Here low ends at 0.
  • (: one open parenthesis and no star, so low and high both end at 1 and the answer is false.
  • ): high becomes -1 right away, so the answer is false.
  • *(: the star comes before the ( and cannot close it, so the answer is false. The range ends at [1, 2].
  • (*) and (*)): the first is true with the star empty. The second is true with the star as (, giving (()).
  • )( followed by stars, such as )(**: high goes negative on the first character, so the answer is false no matter how many stars follow.
  • A string of 10^5 stars: the answer is true. The greedy and stack solutions finish instantly, while the 3^k brute force never would.

Follow-ups interviewers ask

Can you solve it with dynamic programming, and what does it cost?
Yes. Let dp[i][b] say whether the suffix from i can finish when b parentheses are open. Each state has at most three transitions, and b is at most n, so time is O(n^2) and space O(n^2), or O(n) with a rolling row. It is correct but too slow for n = 10^5, and the greedy range replaces the whole table with two numbers.
Why is it safe to say every count between low and high is reachable?
Each character changes the set of reachable counts by shifting it or by widening it with a star. Starting from {0}, a star turns a set {a..b} into {a-1..b+1}, which stays contiguous. A ( or ) shifts the whole set, and clamping at zero removes only the negative end. Contiguous sets are fully described by their endpoints.
How would you also return one valid interpretation?
Use the two-stack method. Record which star each ) borrowed and which star each leftover ( pairs with. Turn those stars into ) or ( and every other star into empty. This takes O(n) time and space, since you must store the choices, which the O(1) space range cannot do.

Valid Parenthesis String FAQ

What is the time complexity of Valid Parenthesis String?

The optimal solution runs in O(n) time with O(1) extra space, where n is the length of the string. It reads each character once and updates two integers. The brute force recursion is O(3^k) for k stars, and a memoised DP is O(n^2).

Why use a greedy range for Valid Parenthesis String?

Only the number of open parentheses matters, and the reachable counts always form a contiguous range. Two integers, the lowest and highest count, describe that range exactly. You reject when the highest count goes below zero and accept when the lowest count is zero at the end.

Can Valid Parenthesis String be solved in O(1) extra space?

Yes. The low and high counters use constant space. A stack or DP table needs O(n), so the greedy range is the only one of these approaches that reaches O(1).

Why does `low` need to be clamped at zero?

A negative open count means a ) had no ( to close, and that reading is invalid, not a state to continue from. Clamping drops those dead readings and keeps the best live ones. Without it, low could be reported as zero or below by a reading that was already broken.

How do I check if a string of parentheses is valid without wildcards?

Scan left to right with one counter. Add one for (, subtract one for ), return false if the counter goes below zero, and return whether it is zero at the end. The wildcard version is the same idea with a range instead of one counter.

Why does the stack solution compare indices at the end?

A star used as ) must come after the ( it closes. If a leftover ( sits at index 5 and the matching star at index 3, that star cannot close it. The comparison open_index > star_index catches that case.

Asked at

See which companies ask this — Pro

Practise it