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.