Skip to content

Minimum Add to Make Parentheses Valid

MediumGreedy
Decode it first. Clues, constraints, pattern and plan before any code.

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

s = "())"    →  1   (add a "(" at the front)
s = "((("    →  3
s = ")("     →  2

Constraints

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