Valid Parenthesis String - Problem

Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.

The following rules define a valid string:

  • Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  • Any right parenthesis ')' must have a corresponding left parenthesis '('.
  • Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  • '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".

Input & Output

Example 1 — Basic Wildcard
$ Input: s = "()"
Output: true
💡 Note: Simple balanced parentheses without any wildcards
Example 2 — Wildcard as Close
$ Input: s = "(*)"
Output: true
💡 Note: The '*' can be treated as ')' to balance the '('
Example 3 — Complex Case
$ Input: s = "(*))"
Output: true
💡 Note: The '*' can be '(' making it '(()))', then balanced by treating another as empty

Constraints

  • 1 ≤ s.length ≤ 100
  • s[i] is '(', ')' or '*'

Visualization

Tap to expand
Valid Parenthesis String ProblemInput: "(*))" → Output: true(*))Wildcard Options:* → (* → )* → emptyChoose * → ( gives: "(())" → Balanced? NoChoose * → ) gives: "())" → Balanced? NoChoose * → empty gives: "())" → Still unbalanced, but greedy finds solution!Result: true
Understanding the Visualization
1
Input
String with '(', ')', and '*' characters
2
Wildcard Flexibility
Each '*' can be '(', ')', or empty
3
Validation
Check if any combination creates valid parentheses
Key Takeaway
🎯 Key Insight: Wildcards provide flexibility - track the range of possible states rather than trying all combinations
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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