![]() |
VOOZH | about |
Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.
Examples:
Input: s = "}{{}}{{{"
Output: 3
Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}".Input: s = "{{"
Output: 1
Explanation: We need 1 reversalInput: s = "{{}{{{}{{}}{{"
Output: -1
Explanation: There's no way we can balance this sequence of braces as the length is odd.
This approach recursively checks all possible ways to reverse brackets to make the expression balanced. The algorithm explores two options for each bracket: keeping it as it is or reversing it. The goal is to find the minimum number of reversals needed to balance the string.
Steps:
-1 because a balanced string requires an even number of brackets.count variable to track the balance of { and }. If at any point the count becomes negative, the string is unbalanced.3
Time complexity: O(2n*n), because O(2n) in recursive function and O(n) in checking the expression generated after every recursive call is balanced or not.
Auxiliary space O(n), because of the Auxillary space of recursion
The solution involves first removing all balanced parts of the expression. For example, converting
"}{{}}{{{"to"}}{{{"by eliminating the balanced part. After this removal, the remaining expression will always have the form}}...}{{...{, consisting of some closing brackets followed by some opening brackets.To balance this remaining expression, we need to calculate the minimum number of reversals required. Let
mbe the number of closing brackets andnbe the number of opening brackets. The minimum reversals required is given byceil(m / 2) + ceil(n / 2).
3
Since the expression only contains one type of bracket, we maintain two variables to keep track of the counts of left (
{) and right (}) brackets as we process the string. If the expression has balanced brackets, we decrement the left variable. Otherwise, we increment the right variable. Finally, the minimum number of reversals required is calculated asceil(left / 2) + ceil(right / 2).
3