#921

Minimum Add to Make Parentheses Valid

Medium
StringStackGreedyGreedyStack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a greedy approach to count the number of unmatched opening and closing parentheses. By keeping track of these counts, we can determine the minimum number of insertions needed to balance the string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two counters: one for unmatched opening parentheses and one for unmatched closing parentheses.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: If the character is '(', increment the unmatched opening counter. If it is ')', check if there is an unmatched opening to pair with; if so, decrement the unmatched opening counter, otherwise increment the unmatched closing counter.
  4. 4Step 4: The result is the sum of unmatched opening and closing counters.
solution.py12 lines
1def minAddToMakeValid(s):
2    open_count = 0
3    close_count = 0
4    for char in s:
5        if char == '(': open_count += 1
6        else:
7            if open_count > 0:
8                open_count -= 1
9            else:
10                close_count += 1
11    return open_count + close_count
12

Complexity note: The time complexity is O(n) because we only make a single pass through the string, counting unmatched parentheses. The space complexity is O(1) since we only use a fixed number of counters.

  • 1Understanding how to balance parentheses is crucial for solving similar problems.
  • 2Using counters to track unmatched parentheses can simplify the problem significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.