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.