Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1249 · Parentheses / Bracket Matching

Minimum Remove to Make Valid Parentheses

LeetCode 1249 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

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

ಮಧ್ಯಮStringStack
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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.