Tensorum
LeetCode 678 · Parentheses / Bracket Matching

Valid Parenthesis String

LeetCode 678 · Medium · solution, intuition & step-by-step walkthrough

Two counters: optimistic opens forward, optimistic closes backward.

MediumStringDynamic ProgrammingStackGreedyBracket Sequences
56 msruntime · beats 6%
48.8 MBmemory · beats 100%
1approach
3accepted runs · last 7 Apr 2024

This is how I solved Valid Parenthesis String (LeetCode 678), a medium problem from the Parentheses / Bracket Matching pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.

Approach

  1. 1

    openCount: +1 for '(' or '*', −1 for ')'.

  2. 2

    closeCount (from the right): +1 for ')' or '*', −1 for '('.

  3. 3

    Either negative → False.

  4. 4

    Earlier version: two stacks of indices.

How I solved it

Two-direction countingPythonO(n) time · O(1) space
class Solution:
    def checkValidString(self, s):
        openCount = 0
        closeCount = 0
        n = len(s)
        for i in range(n):
            if s[i] == "(" or s[i] == "*":
                openCount += 1
            else:
                openCount -= 1
            if s[n - i - 1] == ")" or s[n - i - 1] == "*":
                closeCount += 1
            else:
                closeCount -= 1
            if openCount < 0 or closeCount < 0:
                return False
        return True
Loading the step-through…

Valid Parenthesis String — FAQ

What is the intuition behind Valid Parenthesis String?

Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.

How do you solve Valid Parenthesis String (LeetCode 678)?

1. openCount: +1 for '(' or '*', −1 for ')'. 2. closeCount (from the right): +1 for ')' or '*', −1 for '('. 3. Either negative → False. 4. Earlier version: two stacks of indices.

What is the time and space complexity of Valid Parenthesis String?

Time: O(n). Space: O(1). (Accepted approach: Two-direction counting.)

What are common mistakes in Valid Parenthesis String?

A '*' before a '(' can't close it — the stack version checks index order.