Rearrange given Array such that all set bit positions have higher value than others
Given an array B1[] and a binary array B2[] each of size N, the task is to rearrange array B1[] in a way such that for all setbit position i of B2[] the value of B1[i] will be greater than the values where bit is not set in B2[] i.e for all (i, j) B1[i] > B1[j] when B2[i] = 1, B2[j] = 0 (0 ≤ i, j < N).
Note: If multiple arrangements are possible, print any one of them.
Examples:
Input: N = 7, B1[] = {1, 2, 3, 4, 5, 6, 7}, B2[] = {0, 1, 0, 1, 0, 1, 0}
Output: 1 5 2 6 3 7 4
Explanation: Values having 1 in B2[] array are = {2, 4, 6} and values with 0s are = {1, 3, 5, 7}.
So, in correspondant to B2[] array, B1[] can be rearranged = {1, 5, 2, 6, 3, 7, 4}
B1[] = {1, 5, 2, 6, 3, 7, 4}
B2[] = {0, 1, 0, 1, 0, 1, 0}, now all places in B1[i] > B1[j] where B2[i] = 1, and B2[j] = 0.
It also can be rearranged as {1, 7, 2, 6, 3, 5, 4}Input: N = 3, B1[] = {4, 3, 5}, B2[] = {1, 1, 1}
Output: 5 4 3
Approach: The problem can be solved based on the following idea:
To arrange B1[] as per set bit positions of B2[], sort the values of B1[] and arrange the higher values in positions with bits set and the lower values in positions in other positions.
Follow the steps mentioned below to implement the above idea:
- Make a list of pairs (say v) with the bit value of B2[] and the corresponding value at B1[],
- Sort the list of pairs in ascending order of bits value of B2[].
- Rearrange B1[] using two pointer approach.
- Declare left pointer with 0 and right pointer with N-1.
- When B2[i] is 0 (0 ≤ i < N), set B1[] as v[left] and increment left.
- Otherwise, set B1[i] as v[right] and decrement right.
- Return B1[] as the final answer.
Below is the implementation of the above approach :
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to do required// operationvoid solve(int n, vector<int>& b1, int b2[]){ // Intiliazing vector of pair // to store b2 and b1 array element vector<pair<int, int> > v; int cnt = 1; for (int i = 0; i < n; i++) { // Pushing 1 and 0 integer along with // their corresponding element // in array b1 v.push_back({ b2[i], b1[i] }); } // Sorting the vector of pair // in ascending order sort(v.begin(), v.end()); int left = 0, right = n - 1; // Arranging the array b1 for (int i = 0; i < n; i++) { if (b2[i] == 0) b1[i] = v[left++].second; else b1[i] = v[right--].second; }} // Driver Codeint main(){ int N = 3; vector<int> B1 = { 3, 4, 5 }; int B2[] = { 1, 1, 1 }; solve(N, B1, B2); for (int x : B1) cout << x << " "; return 0;} |
5 4 3
Time Complexity: O(N * logN)
Auxiliary Space: O(N)

