![]() |
VOOZH | about |
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 correspondent 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:
Below is the implementation of the above approach :
5 4 3
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
The approach described here is utilized to reorder an array B1 in a manner dictated by a corresponding flag array B2. Elements in B1 are rearranged such that those associated with a '1' in B2 are placed first, sorted in descending order, and those associated with a '0' are sorted in ascending order and placed afterwards. This method is particularly effective when you need to prioritize certain elements based on binary conditions while maintaining an ordered sequence within those priorities. It is suitable for applications where dynamic reordering is necessary based on external or updated criteria, such as in task scheduling, prioritizing resources, or data processing tasks where order affects output quality or processing efficiency.
Follow the steps to solve the problem:
Below is the implementation of above approach:
5 4 3
Time Complexity: O(NlogN)
Auxilary Space: O(N)