The Minimum Add to Make Parentheses Valid problem involves a string composed of ( and ) characters. A string is "valid" if every opening parenthesis has a matching closing parenthesis in the correct order. Your task is to determine the minimum number of parentheses (either opening or closing) you must add at any position to make the entire string valid.
This is a high-frequency Minimum Add to Make Parentheses Valid interview question because it is a foundational string-parsing problem. Companies like Microsoft and Meta use it to test if a candidate understands stack-based logic or "balance" counters. It's a great "warm-up" problem that can lead to more complex variations involving multiple types of brackets or dynamic programming.
While you can use a Stack, the most memory-efficient Greedy interview pattern involves using two counters: balance and additions.
(, increment the balance.), decrement the balance.balance becomes negative (meaning a ) appeared without a matching (), increment additions and reset balance to 0.additions + balance (the latter representing unclosed ().Take the string ())((.
(: balance = 1.): balance = 0.): balance would be -1. Increment additions = 1, reset balance = 0.(: balance = 1.(: balance = 2.
Final result: additions (1) + balance (2) = 3. We need to add one ( at the start and two ) at the end.)( has equal counts but is invalid.((( also requires three additions at the end.When dealing with parentheses, always think about "balance." Most of these problems can be solved by tracking how many "open" items are currently waiting for a "close" item. Mastering this Minimum Add to Make Parentheses Valid coding problem will help you solve harder problems like "Longest Valid Parentheses."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Score From Removing Substrings | Medium | Solve | |
| Check if a Parentheses String Can Be Valid | Medium | Solve | |
| Minimum Insertions to Balance a Parentheses String | Medium | Solve | |
| Valid Parenthesis String | Medium | Solve | |
| Minimum Number of Swaps to Make the String Balanced | Medium | Solve |