Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 678 · Parentheses / Bracket Matching

Valid Parenthesis String

LeetCode 678 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Two counters: optimistic opens forward, optimistic closes backward.

मध्यमStringDynamic ProgrammingStackGreedyBracket Sequences

मी Valid Parenthesis String (LeetCode 678) असा सोडवला — Parentheses / Bracket Matching पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि 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.

मी कसा सोडवला

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
स्टेप-थ्रू लोड होत आहे…

Valid Parenthesis String — वारंवार विचारले जाणारे प्रश्न

Valid Parenthesis String मागील 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.

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.

Valid Parenthesis String ची time आणि space complexity किती आहे?

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

Valid Parenthesis String मध्ये सामान्य चुका कोणत्या?

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