Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j – i).
Note: A swapped bit can’t be swapped twice and the count of set bit in the given binary string is at most N/2.
Input: S = “1010001”
Following the swapping of characters required:
- Swap characters at indices (0, 1) modifies the string to “0110001” and the cost of this operation is |1 – 0| = 1.
- Swap characters at indices (2, 3) modifies the string to “0101001” and the cost of this operation is |2 – 1| = 1.
- Swap characters at indices (6, 7) modifies the string to “0101010” and the cost of this operation is |7 – 6| = 1.
After the above operations, all the set bits is replaced with unset bits and the total cost of operations is 1 + 1 + 1 = 3.
Input: S = “1100”
Approach: The given problem can be solved using Dynamic Programming by storing the indices of set and unset bits in two auxiliary arrays, say A and B, and then find the sum of the difference between array elements A with any element of the array B. Follow the steps below to solve the given problem:
- Initialize two arrays, say A and B, and store the indices of set and unset bits in it.
- Initialize a 2D array, dp of dimensions K*(N – K) where K is the count of set bit in S such thatdp[i][j] stores the minimum cost of swapping the ith array element A with the jth array element B.
- Now, for each state there are two choices:
- Swap the ith array element A till the (j – 1)th array element B as dp[i][j] = dp[i][j – 1].
- Swap the (i – 1)th array element A till the (j – 1)th array element B and the ith array element A with jth array element B and this state can be calculated as dp[i][j] = dp[i – 1][j – 1] + abs(A[i] – B[i]).
- Now, choose the minimum of the above two choices to find the current state as:
dp[i][j] = min(dp[i][j-1], dp[i-1][j-1] + abs(A[i] – B[j]))
- After completing the above steps, print the value of dp[K][N – K] as the resultant minimum number of operations.
Below is the implementation of the above approach:
Time Complexity: O(K*(N – K)) where K is the count of set bit in S.
Auxiliary Space: O(K*(N – K))
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.