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

Minimum Remove to Make Valid Parentheses

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

Stack of '(' indices; collect unmatched indices; rebuild.

मध्यमStringStack

मी Minimum Remove to Make Valid Parentheses (LeetCode 1249) असा सोडवला — Parentheses / Bracket Matching पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

A ')' with no unmatched '(' before it must go; any '(' still unmatched at the end must go too. A stack of open indices finds both kinds.

Approach

  1. 1

    '(' → push its index.

  2. 2

    ')' → pop if possible, else mark it for removal.

  3. 3

    Mark every index left on the stack.

  4. 4

    Rebuild the string skipping marked indices.

मी कसा सोडवला

Stack of indicesPythonO(n) time
class Solution:
    def minRemoveToMakeValid(self, s):
        stack = []
        indexToBeRemoved = []
        word = ""
        for i in range(len(s)):
            char = s[i]
            if char == "(":
                stack.append(i)
            elif char == ")":
                if not stack:
                    indexToBeRemoved.append(i)  # extra )
                else:
                    stack.pop()
        while stack:
            indexToBeRemoved.append(stack.pop())
        for i in range(len(s)):
            if i not in indexToBeRemoved:
                word += s[i]
        return word
स्टेप-थ्रू लोड होत आहे…

Minimum Remove to Make Valid Parentheses — वारंवार विचारले जाणारे प्रश्न

Minimum Remove to Make Valid Parentheses मागील intuition काय आहे?

A ')' with no unmatched '(' before it must go; any '(' still unmatched at the end must go too. A stack of open indices finds both kinds.

Minimum Remove to Make Valid Parentheses (LeetCode 1249) कसा सोडवावा?

1. '(' → push its index. 2. ')' → pop if possible, else mark it for removal. 3. Mark every index left on the stack. 4. Rebuild the string skipping marked indices.

Minimum Remove to Make Valid Parentheses ची time आणि space complexity किती आहे?

Time: O(n) with a set (O(n²) with indexOf). Space: O(n). (Accepted approach: Stack of indices.)

Minimum Remove to Make Valid Parentheses मध्ये सामान्य चुका कोणत्या?

Checking membership with indexOf on an array is O(n) per character — a set is better.