⚡Flashcard Drill➔
NeetCode #151LC-1249MediumArrays & Hashing
← Back to All Problems

#151 · #1249 · Minimum Remove to Make Valid Parentheses(移除无效的括号)

📌 Problem Statement & Constraints

Given a string s of '(', ')' and lowercase letters, remove the minimum number of parentheses so that the resulting string is valid. Return any valid result. Constraints: 1 <= s.length <= 10^5.

💡 Core Algorithmic Approaches

  1. Scan left to right with a stack of indices of unmatched '('.
  2. On '(', push its index. On ')', pop if the stack is non-empty; otherwise the ')' is unmatched, so mark its index for removal.
  3. After the scan, any indices left on the stack are unmatched '(' and must also be removed.
  4. Build the result by skipping the marked indices. This is the standard minimum-removal greedy.

💻 Benchmark Python3 Implementation

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stack = []                         # indices of unmatched '('
        remove = set()                     # indices to delete
        for i, ch in enumerate(s):
            if ch == "(":
                stack.append(i)
            elif ch == ")":
                if stack:
                    stack.pop()            # matched with the most recent '('
                else:
                    remove.add(i)          # unmatched ')'
        remove.update(stack)               # unmatched '(' left over
        return "".join(ch for i, ch in enumerate(s) if i not in remove)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass to mark and one pass to build the result.
💾 Space Complexity
O(n) for the stack and the removal set.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the leftover '(' on the stack: they are unmatched and must be removed too.
  • Removing letters as well as parentheses: only parentheses may be removed; letters are always kept.
  • Trying to keep the string balanced with the minimum removals by counting alone: you need the positions, not just the counts, to rebuild the string.
  • Using a single counter instead of a stack: it works for this problem (the minimum removal count is determined by counting), but you still need positions to construct the output.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

移除无效的括号

给你一个由 ( 、 ) 和小写字母组成的字符串 s。你需要从字符串中删除最少数目的括号(可以是任意位置的括号),使得剩下的括号字符串有效,并返回任意一个合法字符串。有效的括号字符串应满足:① 空字符串或只包含小写字母的字符串有效;② 若字符串 A 有效,则 (A) 有效;③ 若 A 和 B 有效,则 AB 有效。约束:1 ≤ s.length ≤ 10^5;s[i] 为 ( 、 ) 或小写英文字母。

核心要点

  • 栈标记无效括号(标准解) :用一个栈记录「尚未匹配的左括号下标」。遍历字符串:遇到左括号入栈;遇到右括号时,若栈非空则弹出(配对成功),若栈空则该右括号多余,标记删除。
  • 处理剩余左括号 :遍历结束后,栈中残留的下标即为多余的左括号,全部标记删除。
  • 为什么这样删得最少 :每个多余的右括号必然对应「此刻已无左括号可配对」,无法通过保留来消除;同理,栈中剩余的左括号没有右括号配对。两者的总数即为必须删除的最小数量。
  • 实现 :把字符串转为列表,把待删位置置为空字符串,最后 join。

常见陷阱

  • 忘记清理栈中剩余的左括号 :只处理多余的右括号会留下未匹配的左括号,结果仍无效。
  • 用计数器而非栈 :只统计左右括号数量无法定位 哪个 括号多余。虽然本题只要求返回任一合法串,但用栈定位更精确且是标准解法。
  • 遇到右括号时无条件弹出 : stack.pop() 在栈空时会抛 IndexError。必须先判断 if stack 。
  • 直接对字符串做删除 :字符串不可变,反复切片删除是 O(n²)。必须先转列表。
  • 误以为要删除所有括号 :只删除 无效 的,有效的括号必须保留。

参考实现

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        chars = list(s)
        stack = []                          # 记录未匹配的左括号下标
        for i, c in enumerate(chars):
            if c == '(':
                stack.append(i)
            elif c == ')':
                if stack:
                    stack.pop()             # 配对成功
                else:
                    chars[i] = ''           # 多余的右括号
        for i in stack:                     # 多余的左括号
            chars[i] = ''
        return ''.join(chars)