![]() |
VOOZH | about |
Given 2 arrays arr1[] and arr2[], of size N and M respectively, the task is to find a pair of value (say a and b) such that the following conditions are satisfied:
Examples:
Input: arr1[] = { 6, 9, 7, 8}, arr2[] = {2, 1, 3, 4}
Output: 4 5
Explanation: 4 | 5= 5 and 4 & 5 = 4
Since values of their bitwise OR <= is less than arr1[] elements and also value of their bitwise AND ? less than arr2[] elements.Hence it forms a valid pair. other possible output may be :
4 | 6 = 6 and 4 & 6 =4 Again since 6 is less than arr1[] elements and 4 >= all other arr2[] elements. Hence it also forms a valid pair.Input: arr1[] = {1, 9, 7}, arr2[] = {2, 4, 3}
Output: -1
Explanation: No such pair exists.
Approach: To solve the problem follow the below idea:
Since we know that: (a | b) ? max(a, b) (a & b) ? min(a, b). If we can prove that there exists a pair {a, b} (assuming b > a)such that b ? minimum of all other array OR elements and a ? maximum of all array AND elements then it would also satisfy all other elements
Follow the below steps to solve the problem:
Below is the implementation of the above approach.
-1
Time Complexity: O(N + M) to traverse both arrays and find the minimum and maximum values respectively.
Auxiliary Space: O(N + M) storing both array elements.
Related Articles: