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:

  1. Every opening parenthesis '(' must have a matching closing parenthesis ')'
  2. Every closing parenthesis ')' must have a matching opening parenthesis '('
  3. 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
Dance Partner Matching: "(*))"Step 1: '(' (Male dancer arrives)โ™‚Range: [1, 1] unmatched malesStep 2: '*' (Flexible dancer)?Could be โ™‚: Range [2, 2]Could be โ™€: Range [0, 0]Combined: [0, 2]Step 3-4: ')' ')' (Female dancers)โ™€โ™€Final range: [0, 0] โœ“ Perfect pairing possible!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two variables to track the range

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 100
  • s[i] is '(', ')' or '*'
  • The string contains only parentheses and wildcards
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 25
52.0K Views
Medium-High Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen