FastPrepMinimum Insertions to Balance Parentheses

Minimum Insertions to Balance Parentheses

Google logoGoogle● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Given a string s containing only '(' and ')', return the minimum number of parentheses that must be inserted at any positions to make the string valid.

A valid parenthesis string has every opening parenthesis matched with a later closing parenthesis, and every closing parenthesis matched with an earlier opening parenthesis.

Function

minInsertionsToBalance(s: String) → int

Examples

Example 1

s = "())"return = 1

Insert one opening parenthesis before the final closing parenthesis.

Example 2

s = "((("return = 3

Each unmatched opening parenthesis needs a closing parenthesis.

Example 3

s = "()"return = 0

The string is already valid.

Constraints

  • 0 <= s.length <= 100000.
  • s contains only '(' and ')'.

More Google problems

See Google hiring insights
public int minInsertionsToBalance(String s) {
    // Write your code here.
}
s"())"
expected1
Checking account…