Handle Score
@Ibrahim Nash 6420
@blackshadows 6380
@mb1973 5642
@Quandray 5233
@akhayrutdinov 5111
@saiujwal13083 4610
@sanjay05 3762
@kirtidee18 3673
@marius_valentin_dragoi 3522
@sushant_a 3459
@verma_ji 3413
Complete Leaderboard
Count the Reversals
Medium Accuracy: 55.17% Submissions: 1416 Points: 4

Given a string S consisting of only opening and closing curly brackets '{' and '}', find out the minimum number of reversals required to convert the string into a balanced expression.
A reversal means changing '{' to '}' or vice-versa.

Example 1:

S = "}{{}}{{{"
Output: 3
Explanation: One way to balance is:
"{{{}}{}}". There is no balanced sequence
that can be formed in lesser reversals.

​Example 2:

S = "{{}{{{}{{}}{{"
Output: -1
Explanation: There's no way we can balance
this sequence of braces.

Your Task:
You don't need to read input or print anything. Your task is to complete the function countRev() which takes the string S as input parameter and returns the minimum number of reversals required to balance the bracket sequence. If balancing is not possible, return -1. 

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).

1 ≤ |S| ≤ 105


to report an issue on this page.


We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?


All Submissions

My Submissions:

Login to access your submissions.

Count the Reversals

Output Window