Skip to content
Decoder

Minimum Add to Make Parentheses Valid

Medium

Problem

s contains only ( and ). In one move you may insert one bracket anywhere in the string. Return the fewest moves that make s balanced.

Example 1

Input
s = "())"
Output
1
Why
add a "(" at the front

Example 2

Input
s = "((("
Output
3

Example 3

Input
s = ")("
Output
2

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.