illuminati

1 min

Minimum Parantheses! - InterviewBit Solution

Problem: Minimum Parantheses!

Problem Description:

Given a string A of parentheses ‘(‘ or ‘)’.
 
The task is to find a minimum number of parentheses ‘(‘ or ‘)’ (at any positions) we must add to make the resulting parentheses string valid.
 
A string is valid if:

  • Open brackets must be closed by the corresponding closing bracket.

  • Open brackets must be closed in the correct order.

Problem Constraints

  • 1 <= |A| <= 1e5

  • A[i] = '(' or A[i] = ')'
     

Input Format

The first and only argument is a string A.

Output Format

Return a single integer denoting the minimum number of parentheses ‘(‘ or ‘)’ (at any positions) we must add in A to make the resulting parentheses string valid.

Example Input

Input 1:
 
A = "())"
 

 
Input 2:
 
A = "((("

Example Output

Output 1:
 
1
 

 
Output 2:
 
3

Example Explanation

Explanation 1:
 
One '(' is required at the beginning.
 

 
Explanation 2:
 
Three ')' is required at the end.

Solution Approach:

Solution:

Code in C++

If you have any questions or queries, feel free to drop a comment in the comments section below.

Note: Help us improve this blog

If you have a better solution, and you think you can help your peers to understand this problem better, then please drop your solution and approach in the comments section below.

We will upload your approach and solution here by giving you the proper credit so that you can showcase it among your peers.