Skip to main content
Back to problems
Leetcode
Medium
Strings
Stacks
Greedy
Minimum Add To Make Parentheses Valid

Given a string of parentheses, add the fewest characters needed so every opening parenthesis has a matching closing parenthesis and the final string is valid.

Acceptance 0%
Problem Statement

Problem

You are given a string s containing only the characters '(' and ')'.

In one move, you may add a parenthesis character at any position in the string.

Return the minimum number of characters that must be added so that the resulting string is a valid parentheses string.

A parentheses string is valid when:

  • every '(' has a matching ')', and
  • matching pairs are properly nested.

Goal

Compute the smallest number of insertions needed to make the string balanced.

Input Format

  • A single string s consisting only of '(' and ')'.

Output Format

  • Return one integer: the minimum number of parentheses that must be inserted.

Constraints

  • 1 <= s.length
  • s contains only '(' and ')'
  • The answer fits in a 32-bit signed integer.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "())"

Output

1

Explanation

The string has one extra closing parenthesis. Adding one '(' at the beginning makes it valid: "(())".

Example 2

Input

s = "(("

Output

2

Explanation

Both opening parentheses are unmatched, so two closing parentheses must be added: "(())".

Show 1 more example

Example 3

Input

s = "()))(("

Output

4

Explanation

Two insertions are needed for the extra closing parentheses and two more are needed to match the remaining opening parentheses.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.