Back to Parenthesis
Parenthesis
Medium

Valid Parenthesis String

LAB

Return true if * can be treated as (, ), or empty to make s a valid parentheses string.

EXAMPLES

Example 1
Input
{
  "s": "(*)"
}

Output
true

FUNCTION SHAPE

s: stringbool
SOLUTION NOTE

Greedy two-pass: first pass treats '*' as '(', second pass treats '*' as ')'. Both must succeed.

Reveal reference solution +
pythonREFERENCE
def checkValidString(self, s: str) -> bool:
    def check(s, open_char):
        balance = 0
        for c in s:
            balance += 1 if c == open_char or c == '*' else -1
            if balance < 0:
                return False
        return True

    return check(s, '(') and check(s[::-1], ')')
TimeO(n)
SpaceO(1)
Open on LeetCode
00:00
4 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.