Wildcard Brackets: Can the Sequence Be Made Valid?
Greedy & IntervalsAuto-graded · 26 test casesLast updated
Decide if a string of brackets and wildcards can be made valid by choosing each wildcard's role, testing range-tracking of reachable open counts or a greedy two-pass argument.
You are given a string pattern consisting only of the characters (, ) and *. The * character is a wildcard: you may independently choose to treat each one as an opening bracket (, a closing bracket ), or as nothing at all (it is deleted).
Determine whether some choice of roles for the wildcards produces a valid bracket sequence.
A bracket sequence is valid when both of the following hold:
- While reading from left to right, the number of
)seen so far never exceeds the number of(seen so far. - At the end, the total number of
(equals the total number of).
The empty sequence is valid.
Function
def wildcard_valid(pattern: str) -> bool:
Return True if at least one assignment of roles to the wildcards gives a valid sequence, and False otherwise.
Rules
- Each wildcard is decided separately, so different wildcards may take different roles.
- Existing
(and)characters are never changed or moved. - A sequence in which the
)count exceeds the(count at any prefix is invalid, even if the totals are equal at the end.
Constraints
1 <= len(pattern) <= 100- Every character of
patternis one of(,)or*.
Examples
Example 1
Input: wildcard_valid('(*))')
Output: True
Example 2
Input: wildcard_valid(')*(')
Output: False
Example 3
Input: wildcard_valid('*(*')
Output: True
Hints
Hint 1
Trying every role for every wildcard is exponential. Think about what you really need to know after reading a prefix: how many unmatched `(` could be pending.
Hint 2
The set of possible pending-open counts after each prefix is a contiguous range. Track only its smallest and largest values.
Hint 3
A `(` shifts the range up by one, a `)` shifts it down by one, and a `*` widens it by one on each side. Counts below zero are illegal and must be dropped, and if even the largest value goes below zero you can stop with False.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Rather than choosing a role for each wildcard, track the set of pending-open counts (unmatched () that are achievable after each prefix while never going negative. This set is always a contiguous range [low, high], so two integers describe it completely.
For each character:
(: bothlowandhighincrease by 1.): both decrease by 1.*:lowdecreases by 1 (wildcard as)) andhighincreases by 1 (wildcard as(). The "nothing" option keeps values already inside the range.
After each update:
- If
high < 0, even treating every wildcard so far as(cannot cover the)characters, so returnFalse. - If
low < 0, setlow = 0, because negative counts correspond to invalid prefixes and must be discarded.
At the end, the sequence can be made valid exactly when a pending count of 0 is reachable. Since low is clamped to be at least 0, this means low == 0.
Why it is correct
Let R_i be the set of non-negative pending counts reachable after i characters.
R_0 = {0}.- A
(or)shifts every element by one, which keeps an interval an interval. - A
*maps eachxto{x-1, x, x+1}. The union of these over a contiguous range[a, b]is[a-1, b+1], still contiguous. - Removing negative values intersects the interval with
[0, ∞), giving[max(low, 0), high], which is empty exactly whenhigh < 0.
So [low, high] represents every achievable state. The prefix rule is enforced by the filtering at each step, and the final equality rule means 0 must lie in the final range, which is equivalent to low == 0.
The clamp is essential: without it, a path that dipped below zero could later "recover" through an illegal route.
Complexity
- Time: O(n), one pass with constant work per character.
- Space: O(1).
Reference solution
def wildcard_valid(pattern: str) -> bool:
# [low, high] is the range of non-negative pending-open counts
# reachable after the prefix read so far.
low = high = 0
for ch in pattern:
if ch == '(':
low += 1
high += 1
elif ch == ')':
low -= 1
high -= 1
else: # wildcard: '(' , ')' or nothing
low -= 1
high += 1
if high < 0:
# Even with every wildcard as '(', there are too many ')'.
return False
if low < 0:
# Negative counts are illegal prefixes; discard them.
low = 0
return low == 0