Community Problem

Min Add to Make Parentheses Valid

Difficulty: Medium

Count the minimum number of '(' and ')' insertions that turn a parenthesis string valid using a single-pass two-counter scan.

Min Add to Make Parentheses Valid

Count the minimum number of '(' and ')' insertions that turn a parenthesis string valid using a single-pass two-counter scan.

MEDIUM
Free
stack
greedy
strings
kavyachakraborty

By @kavyachakraborty

January 3, 2026

·

Updated May 18, 2026

1,200 views

27

4.6 (10)

This is a Series B onsite favorite because it tests whether a candidate reaches for a stack reflexively or notices the simpler counter pattern. I always pause and ask: do you actually need to know WHICH characters survive, or just HOW MANY of each kind to add? The latter is two integers and one pass.

Min Add to Make Parentheses Valid

A parenthesis string is valid if every '(' has a matching ')' to its right and every ')' has a matching '(' to its left. Given a string s consisting only of '(' and ')', return the minimum number of single-character insertions (of either '(' or ')') needed to make s valid.

Insertions can be made anywhere in the string. The original characters cannot be reordered or deleted.

Examples

Example 1:

  • Input: s = "())"
  • Output: 1
  • Explanation: Insert one '(' to get "(())". One insertion suffices.

Example 2:

  • Input: s = "((("
  • Output: 3
  • Explanation: Insert three ')' to get "((()))".

Example 3:

  • Input: s = "()"
  • Output: 0
  • Explanation: Already valid.

Example 4:

  • Input: s = "()))(("
  • Output: 4
  • Explanation: Two ')' are unmatched on the left and two '(' are unmatched on the right.

Constraints

  • 1 <= s.length <= 1000
  • s[i] is '(' or ')'.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems