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.