Valid Parenthesis String - Problem
Imagine you're a compiler trying to validate parentheses in code, but with a twist! You're given a string s containing only three types of characters: opening parenthesis '(', closing parenthesis ')', and a wildcard '*'.
Your task is to determine if this string can be made valid by treating each * as either:
- An opening parenthesis
'(' - A closing parenthesis
')' - An empty string (ignore it completely)
A valid parentheses string follows these rules:
- Every opening parenthesis
'('must have a matching closing parenthesis')' - Every closing parenthesis
')'must have a matching opening parenthesis'(' - Opening parentheses must come before their corresponding closing parentheses
Goal: Return true if the string can be made valid, false otherwise.
Input & Output
example_1.py โ Basic wildcard usage
$
Input:
s = "()"
โบ
Output:
true
๐ก Note:
Simple valid parentheses without wildcards
example_2.py โ Wildcard as closing bracket
$
Input:
s = "(*)"
โบ
Output:
true
๐ก Note:
The '*' can be used as ')' to close the opening '('
example_3.py โ Multiple wildcards
$
Input:
s = "(*))"
โบ
Output:
true
๐ก Note:
First '*' can be '(' and we get "(())" which is valid
Visualization
Tap to expand
Understanding the Visualization
1
Count potential partners
Track minimum and maximum possible male dancers waiting
2
Process each dancer
Males increase count, females decrease count, flexible dancers create a range
3
Check feasibility
If we ever have too many females (negative max), it's impossible
4
Final validation
Check if perfect pairing (0 unmatched) is within our range
Key Takeaway
๐ฏ Key Insight: Instead of trying every combination, track the range of possibilities. Wildcards create flexibility, but we only need to know if perfect pairing (0 unmatched) is achievable within our range.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, constant work per character
โ Linear Growth
Space Complexity
O(1)
Only using two variables to track the range
โ Linear Space
Constraints
- 1 โค s.length โค 100
- s[i] is '(', ')' or '*'
- The string contains only parentheses and wildcards
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code