VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-pair-whose-bitwise-or-and-bitwise-and-follows-the-given-condition/

⇱ Find pair whose bitwise OR and bitwise AND follows the given condition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find pair whose bitwise OR and bitwise AND follows the given condition

Last Updated : 23 Jul, 2025

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:

  1. (a | b) ? arr1[i] for all values of i in the range [0, N-1].
  2. (a & b) ? arr2[j] for all values of j in the range [0, M-1].

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:

  • Find the minimum element of the first array and the maximum element of the second array.
  • Then check the condition, if b ? a then print b and a.
  • Otherwise, print "-1".

Below is the implementation of the above approach.


Output
-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:

Comment