NeetCode #369LC-921MediumStack
← Back to All Problems#369 · #921 · Minimum Add to Make Parentheses Valid(使括号有效的最少添加)
📌 Problem Statement & Constraints
A parentheses string is valid if it is empty, or can be written as
AB or (A) where A and B are valid. Given a string s, return the minimum number of parentheses to insert to make it valid. Constraints: 1 <= s.length <= 1000.💡 Core Algorithmic Approaches
- Scan left to right with a counter of unmatched opening brackets.
- On
(, increment. On), decrement if possible; if there is nothing to match, that)must be fixed by an insertion, so increment the answer. - At the end, any unmatched
(also needs one insertion each. - The answer is
insertions_for_closing + unmatched_opening.
💻 Benchmark Python3 Implementation
class Solution:
def minAddToMakeValid(self, s: str) -> int:
opening = 0 # unmatched '(' so far
need = 0 # insertions needed for stray ')'
for ch in s:
if ch == "(":
opening += 1
elif opening > 0:
opening -= 1 # matched
else:
need += 1 # unmatched ')' -> insert a '('
return need + opening # plus one insertion per leftover '('⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two counters, no stack needed since only the counts matter.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the leftover opening brackets: they each need one closing insertion.
- Using a stack: it works but uses O(n) space for information that two counters capture.
- Decrementing
openingbelow zero: that would conflate stray)with matched pairs; theelsebranch is required. - Assuming the answer is
abs(balance): that ignores the order, so")("would give 0 instead of the correct 2.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
使括号有效的最少添加
只有满足下面几点之一,括号字符串才是有效的:它是一个空字符串;或者它可以被写成 AB (A 与 B 都是有效字符串);或者它可以被写作 (A) ,其中 A 是有效字符串。给定一个括号字符串 s,在每一次操作中,你都可以在字符串的任何位置插入一个括号。例如,如果 s = "()))" ,你可以插入一个开始括号为 "(()))" 或结束括号为 "())))" 。返回 使结果字符串有效 的 最少 添加次数。约束:1 ≤ s.length ≤ 1000;s[i] 为 ( 或 ) 。
核心要点
- 一次遍历计数(标准解) :维护 need_left (需要的左括号数,即未匹配的右括号数)与 balance (当前未匹配的左括号数)。
- 遇到 ( : balance += 1 。
- 遇到 ) :若 balance > 0 则 balance -= 1 (匹配成功);否则 need_left += 1 (需要补一个左括号)。
- 答案 : need_left + balance ——前者是必须补的左括号数,后者是最终未闭合的左括号数(需要补等量的右括号)。
常见陷阱
- 答案只返回 balance 或只返回 need_left :两者都要计入——未匹配的右括号需要补左括号,未闭合的左括号需要补右括号。
- 用栈实现 :可以(栈空时遇到 ) 就计数),但计数器方案空间 O(1) 更优。
- 误以为要用 20 题的「判断是否有效」思路 :本题求的是「最少添加数」,不是「是否有效」。
- need_left 与 balance 的含义混淆 : need_left 是「需要添加的左括号数」, balance 是「需要添加的右括号数」。
参考实现
class Solution:
def minAddToMakeValid(self, s: str) -> int:
need_left = 0 # 未匹配的右括号数(需要补左括号)
balance = 0 # 当前未匹配的左括号数
for c in s:
if c == '(':
balance += 1
else:
if balance > 0:
balance -= 1 # 匹配成功
else:
need_left += 1 # 需要补一个左括号
return need_left + balance # 补左括号 + 补右括号