Given an expression consisting of an opening brace { and a closing brace }, find the minimum number of inversions needed to balance the expression.

For example,

Input:  {{}{{}{{
Output: Minimum number of inversions needed is 2
 
{{}{{}{{ ——> {{}{{}}{ ——> {{}{{}}}
 
 
Input:  {{{{{{
Output: Minimum number of inversions needed is 3
 
{{{{{{ ——> {{{}{{ ——> {{{}}{ ——> {{{}}}

Practice this problem

The idea is to traverse the given expression and maintain a count of open braces in the expression seen.

  1. If the current character is an opening brace {, increment the opened braces count by 1.
  2. If the current character is a closing brace }, check if it has an unclosed brace to its left (look for non-zero opened brace count).
    1. If any unclosed brace is found, close it using the current brace and decrement the count of opened braces by 1.
    2. Otherwise, convert the current closing brace } to { and increment the total inversions needed and the opening brace count by 1.
  3. After we are done processing each character in the expression, if there are n opened braces, we will need exactly n/2 inversion to close them.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The minimum number of inversions needed is 2

Java


Download  Run Code

Output:

The minimum number of inversions needed is 2

Python


Download  Run Code

Output:

The minimum number of inversions needed is 2

The time complexity of the above solution is O(n), where n is the length of the input expression, and doesn’t require any extra space.