All problems

Problem 131

Minimum Add to Make Parentheses Valid

Medium · 20 pts · String, Stack, Greedy

Problem

You are given a string of '(' and ')' characters. Find the minimum number of parentheses you need to insert, at any positions, to make it a valid parentheses string, where every '(' is closed by a later ')' and every ')' closes an earlier '('. Scan from left to right and keep a count of open brackets. A ')' with no open bracket to close needs an inserted '(' before it. At the end, every '(' that is still open needs an inserted ')'.

Input

A single string of '(' and ')'.

Output

Print the minimum number of insertions.

Constraints

1 <= length <= 100000

Example input

())

Example output

1

Explanation

In "())", the first ')' closes the '(' but the second ')' has nothing to close. Inserting one '(' fixes it, giving "(())", so the answer is 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Largest Rectangle in Histogram Next: Longest Valid Parentheses