Given a binary string S of length N and an integer K, the task is to find the minimum number of adjacent swaps required to make the binary string divisible by 2K. If it is not possible then print -1.
Input: S = “100111”, K = 2
Swapping the right-most zero 3 times
to the right, we get “101110”.
Swapping the second right-most zero
3 times to the right, we get “111100”.
Input: S = “1011”, K = 2
Method 1: An approach will be swapping from the right-most zero. So, let’s rephrase the problem to something more simpler. The minimum number of swaps are required such that at least K consecutive zeros are made available at the right end.
One way will be to simulate the swapping. Starting from the right-most zero, swap it till it has 1 at its right and its not the end of the string. This will be performed for the K rightmost zeros. The time complexity of this approach will be O(N * K).
Method 2: The key for performing better here will be to avoid doing the simulation.
Among the K right-most zeros, each zero will need to be swapped X number of times, where X is the number of 1s to the right of that zero.
Thus, for the K right-most zeros, the task is to find the sum of the number of 1s to the right of each of them.
- Initialise variable c_zero = 0, c_one = 0 and ans = 0.
- Run a loop from i = N – 1 to i = 0.
- If S[i] = 0 then update c_zero = c_zero + 1 and ans = ans + c_one.
- If S[i] = 1 then update c_one = c_one + 1.
- If c_zero = K then break.
- If c_zero < K then return -1.
- Finally, return the ans.
Thus, the time complexity of this approach will be O(N).
Below is the implementation of the above approach:
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.