Rearrange given binary strings to maximize their Bitwise XOR value
Input: S1 = “1001”, S2 = “0010”, S3 = “1110”
Rearrange the digits of S1 as “1010”, S2 as “1000” and S3 as “1101”.
The XOR of these strings is “1111” which is 15 in decimal form.
Input: S1 = “11111”, S2 = “11111”, S3 = “11111”
There is no other way to arrange the digits. Hence, XOR is “11111” which is 31 in decimal form.
Naive Approach: The simplest approach is to generate all possible ways to rearrange S1, S2, and S3. Suppose there are O1, O2 and O3 set bits in the strings S1, S2, and S3 respectively. The total number of rearrangements to check to get the maximum Bitwise XOR value is as follows:
Total ways to rearrange S1 = NCO1
Total ways to rearrange S2 = NCO2
Total ways to rearrange S3 = NCO3
Hence, total possible rearrangements to check = NCO1*NCO2 * NCO3
Time Complexity: O((N!)3), where N is the length of the given strings.
Auxiliary Space: O(N)
Efficient Approach: The idea is to find a suitable rearrangement of S1, S2, and S3 such that their Bitwise XOR value is maximized using Dynamic Programming. The subproblems can be stored in a dp table where dp[i][o1][o2][o3] stores the maximum XOR value up to position N-1 starting from the index i, where o1 is, o2 and o3 are the number of 1s still remaining to be placed in strings S1, S2 and S3 respectively.
There can be four cases possible at any position i from 0 to (N – 1):
- Assign 1s to all the three strings
- Assign 1s to any two strings
- Assign 1s to any one of the strings.
- Assign 0s to all the strings.
From the above possible cases for each position, calculate the maximum Bitwise XOR obtainable from the four possibilities:
Follow the steps below to solve the problem:
- Initialize a table dp to store the number of ones in S1, S2 and S3 for the positions i from 0 to N-1.
- The transition states is as follows:
dp[i][o1][o2][o3] = max(dp(assign 1s to all three strings), dp(assign 1s to any of the two strings), dp(assign 1s to any one string), dp(do not assign 1 to any string)) where,
i = current position
o1 = remaining ones to be placed in the string S1
o2 = remaining ones to be placed in the string S2
o3 = remaining ones to be placed in the string S3
- Solve the subproblems for all cases using the above transition and print the maximum XOR value amongst them.
Below is the implementation of the above approach:
Time Complexity: O(N4)
Auxiliary Space: O(N)
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.