Minimize cost of flipping or swaps to make a Binary String balanced
Given a binary string S of size N(where N is even), the task is to find the minimum cost of making the given binary string balanced by flipping one of the adjacent different characters at the cost of 1 unit or swap the characters at indices i and j such that (i < j) at the cost of (j – i) unit. If it is impossible to make the string balanced, the print “-1”.
A binary string is balanced if it can be reduced to an empty string by deleting two consecutive alternating characters at once and then concatenating the remaining characters.
Input: S = “110110”
Explanation: Following operations are performed:
Operation 1: As the adjacent characters at indices 0 and 1 are different, flipping S modifies S to “010110”. Cost = 1.
After completing the above operations, the given string becomes balanced, as it can be reduced to an empty string by deleting two consecutive alternating characters.
Therefore, the total cost is 1.
Input: S = “11100”
Approach: The given problem can be solved based on the observations that the flipping of the adjacent different characters is more optimal than using the swapping of characters and the position of 0s and 1s in the string does not matter. Follow the steps below to solve the problem:
- If all the characters are equal, then it is impossible to make the string balanced. Therefore, print “-1”.
- Store the count of 1s and 0s in variables, say count1 and count0 respectively.
- Store the absolute difference of count1 and count0 in a variable K.
- Now, flip the K/2 characters to make the string balanced and print the value of K/2 as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.