Minimum Remove to Make Valid Parentheses
LeetCode 1249 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Stack of '(' indices; collect unmatched indices; rebuild.
నేను 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
'(' → 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.
నేను ఎలా పరిష్కరించాను
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 wordMinimum 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.