AAlgoLoopSpaced repetition for LeetCode
MEDIUMGreedyLeetCode ↗

Valid Parenthesis String

The key idea

Each '*' is a wildcard: '(', ')', or empty. Instead of trying every choice, track the RANGE of possible open-paren counts as [low, high]. low assumes every '*' so far closed; high assumes every '*' opened. The string is valid iff this range can reach exactly zero, never letting low go negative.

Problem

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

The string is valid if all of the following rules hold:

- 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 ')'.
- A '*' could be treated as a single right parenthesis ')', a single left parenthesis '(', or an empty string "".

Constraints

Examples

Input: s = "()" Output: true
Input: s = "(*)" Output: true
Input: s = "(*))" Output: true

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Greedy problems