Minimum Insertions to Balance a Parentheses String

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

In this variant of balanced parentheses, every '(' must be closed by **two consecutive** '))' that appear after it. A string is balanced when its characters can be matched this way, with proper nesting. For example "())", "())(())))", and "(())())))" are balanced, while ")()", "()))", and "(()))" are not. Given a string s of '(' and ')', you may insert either character at any position. Return the minimum number of insertions needed to make s balanced. Aim for a single O(n) pass.

Examples

Input: s = "(()))"
Output: 1
The inner '(' is closed by the first '))', and the outer one needs one more ')' appended.
Input: s = "())"
Output: 0
Already balanced.
Input: s = "))())("
Output: 3
Insert '(' at the front to close the leading '))', and append '))' to close the final '('.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of '(' and ')' only

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