Minimum Add to Make Parentheses Valid

MediumStackgreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A parentheses string is *valid* if it is empty, or it is A + B where A and B are valid, or it is "(" + A + ")" where A is valid. Given a string s of '(' and ')' characters, you may insert a parenthesis at any position, any number of times. Return the minimum number of insertions needed to make s valid.

Examples

Input: s = "())"
Output: 1
Insert "(" before the last ")" (or at the front).
Input: s = "((("
Output: 3
Each "(" needs its own ")".

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems