Input: N = 4, X = 2, S = "1100"
Output: 2
Explanation:
- First operation: i = 1 and j = 3 as (i%X == j%X == 1). So, update S1 = S1⊕S3 = 1. Then S = 1110
- Second operation: i = 2 and j = 4 as (i%X == j%X == 0). So, update S2 = S2⊕S4 = 1. Then S = 1111. Now all the characters are turned into 1. Therefore, the minimum number of operations required is 2.
Input: N = 6, X = 4, S = "100101"
Output: 6
Explanation: It can be verified that, If operations are performed optimally, Then the minimum operations required will be 6.
The problem is based on the Bitwise Concept and can be solved using some observations.
XOR of same characters is 0 and XOR of different characters is 1. We can do XOR operations on particular set of characters.
For Example: If X = 2, then we can do XOR on 1st, 3rd, 5th.. or 2nd, 4th, 6th... and so on.
There can be two cases: Either we can make all character to ones or all characters to zeroes.
- If we want to make all characters in a set to 1: then there should to at least one '1' in that set. If not, then it is impossible to make all characters equal to '1'.
- If we want to make all characters in a set to 0: then if the number of '1' in that set is even, then the number of operations are half of the number of '1' else we have to add 2 more operations to make the one remaining '1' in that set to '0' using some other '0' in that set by XORing the '0' with '1' two times.
ie. [1,0] -> 1 ^ 0 = 1; [1,1] -> 1 ^ 1 = 0; [0,0].
It takes one operation to convert [1,0] to [1,1] and one operation to convert [1,1] to [0,0]. So, it takes two operations to convert [1,0] to [0,0].