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 - Greedy Approach INPUT String s = "()" ( index 0 ) index 1 Character Types: '(' - Left paren ')' - Right paren '*' - Wildcard Input Value: s = "()" ALGORITHM STEPS 1 Initialize Counters lo = 0, hi = 0 (min/max open parens) 2 Process '(' lo++, hi++ (both +1) lo=1, hi=1 3 Process ')' lo--, hi-- (both -1) lo=0, hi=0 4 Check Validity If hi < 0: invalid Keep lo >= 0 Balance Range Tracking [lo, hi] = [0, 0] 0 in range means valid! FINAL RESULT true Valid String Why Valid? 1. Every '(' has matching ')' 2. Balance never goes negative 3. Final lo = 0 (balanced) 4. hi never went below 0 Output: true Key Insight: Track a RANGE [lo, hi] of possible open parenthesis counts. For '(' both increase, for ')' both decrease, for '*' lo decreases and hi increases (wildcard flexibility). String is valid if 0 can be in final range (lo == 0). Time: O(n), Space: O(1). TutorialsPoint - Valid Parenthesis String | Greedy - Balance Range Tracking
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