← 返回 meta 的题目列表Minimum Add to Make Parentheses Valid
类型:qbank
LC 921 — count the minimum insertions (of `(` or `)`) needed to make a parens string valid. Surfaced as the first E5 phone-screen problem.
Requirements
Input: string s containing only ( and ).
Return the minimum number of insertions needed so that every ( has a matching ) and vice versa.
Notes
Linear scan with two counters: open_needed for unmatched ) seen so far, close_needed for currently open (. Final answer is the sum.
Equivalent to maintaining a single signed balance, clamping to 0 whenever it goes negative and adding the underflow to the answer.
Common follow-up direction: return the actual inserted string, not just the count.
Preparation
Drill both this and LC 1249 (Min Remove to Make Valid Parens) together — they share the balance trick and interviewers occasionally splice their follow-ups.