Open In App

Check if any Array pair has bitwise XOR greater than bitwise AND

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the task is to find if there exists a pair in the array, such that their bitwise XOR is greater than their bitwise AND i.e. arr[i] ⊕ arr[j] > arr[i] & arr[j], (0 ≤ i < j ≤ N-1) where ⊕ represents the Bitwise XOR operator and & represents bitwise AND operator.

Examples:

Input: arr[] = {4, 5, 8, 6}
Output: Yes
Explanation: Bitwise XOR of 4 and 8 is 12 and bitwise AND = 0.

Input: arr[] = {5, 4, 7, 6}
Output: No

 

Naive Approach: The approach to this problem is to find all the possible pairs and check if any of the pairs has bitwise XOR greater than bitwise AND.

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check
// if a pair is present or not
bool checkPair(int* arr, int N)
{
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
            int xorr = arr[i] ^ arr[j];
            int and = arr[i] & arr[j];
 
            if (xorr > and)
                return true;
        }
    }
 
    return false;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 5, 8, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    if (checkPair(arr, N))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}


Java




import java.util.Arrays;
 
public class Gfg {
    // Function to check
    // if a pair is present or not
    static boolean checkPair(int[] arr, int N)
    {
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                int xorr = arr[i] ^ arr[j];
                int and = arr[i] & arr[j];
 
                if (xorr > and)
                    return true;
            }
        }
 
        return false;
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 4, 5, 8, 6 };
        int N = arr.length;
 
        // Function call
        if (checkPair(arr, N))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}


Python3




# Python code to implement the above approach
 
# Function to check
# if a pair is present or not
def checkPair( arr,  N):
    for i in range(0,N):
        for j in range(i+1,N):
            xorr = arr[i] ^ arr[j];
            and = arr[i] & arr[j];
 
            if (xorr > and):
                return True;
    return False;
 
# Driver Code
arr = [ 4, 5, 8, 6 ];
N = len(arr);
 
# Function call
if (checkPair(arr, N)):
    print("Yes");
else:
    print("No");
 
    # This code is contributed by ratiagrawal.


C#




using System;
 
class Gfg {
    // Function to check
    // if a pair is present or not
    static bool checkPair(int[] arr, int N)
    {
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                int xorr = arr[i] ^ arr[j];
                int and = arr[i] & arr[j];
 
                if (xorr > and)
                    return true;
            }
        }
 
        return false;
    }
 
    public static void Main()
    {
        int[] arr = { 4, 5, 8, 6 };
        int N = arr.Length;
 
        // Function call
        if (checkPair(arr, N))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}


Javascript




// Javascript code to implement the above approach
 
// Function to check
// if a pair is present or not
function checkPair( arr,  N)
{
    for (let i = 0; i < N; i++) {
        for (let j = i + 1; j < N; j++) {
            let xorr = arr[i] ^ arr[j];
            let and = arr[i] & arr[j];
 
            if (xorr > and)
                return true;
        }
    }
 
    return false;
}
 
// Driver Code
let arr = [ 4, 5, 8, 6 ];
let N = arr.length;
 
// Function call
if (checkPair(arr, N))
    console.log("Yes");
else
    console.log("No");


Output

Yes

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The problem can be solved efficiently based on the following idea:

The idea is built on the observation that:

  • Bitwise XOR of two same bits is always 0, i.e. 1⊕1 = 0⊕0 = 0 and XOR of two different bit is 1.
  • Bitwise AND of two same bits are same as that bit i.e. 1⊕1 = 1 and 0⊕0 = 0 and AND of different bits is always 0.

Now from the above observation, it can be said that if the MSB (Most significant bit) of two numbers are at different positions then their bitwise XOR will be greater than bitwise AND because.

  • The MSB will be the XOR of two different bits which will result in a set bit and bitwise AND of two different bits will be a 0.
  • The MSB of bitwise XOR will be a greater power than the MSB of bitwise AND.

So to find if such a pair is possible check the conditions only for the minimum and the maximum of the array because they are the extreme values of the array. If they have the MSB in the same positions then all other between them will have the MSB in that position and bitwise XOR will never be greater than the bitwise AND for any pair. In all other cases such a pair is possible.

Follow the steps mentioned below to implement the approach:

  • Initialize Min and Max to store the maximum and minimum elements of the array.
  • Traverse the array arr[] from i = 0 to N-1:
    • Store the maximum element in Max and the minimum element in Min.
  • Now check the number of count bits of Min and Max.
    • If count of Bit of Max ≠ count of Bit of Min, then print YES (because then MSB of Max will be in a different position than MSB of Min).
    • Else print NO.

Below is the implementation of the above approach:

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of bit
int countBit(int n)
{
    int Count = 0;
    while (n) {
        n /= 2;
        Count++;
    }
    return Count;
}
 
// Function to check
// if a pair is present or not
bool checkPair(int* arr, int N)
{
    int Min = INT_MAX;
    int Max = INT_MIN;
 
    // Find Maximum and Minimum element
    // of the array
    for (int i = 0; i < N; i++) {
        Min = min(Min, arr[i]);
        Max = max(Max, arr[i]);
    }
 
    // Check if max and min element have
    // different count of bits
    // then return 1 else return 0
    if (countBit(Min) != countBit(Max))
        return true;
    else
        return false;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 5, 8, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    if (checkPair(arr, N))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}


Java




// Java code to implement the above approach
import java.io.*;
 
class GFG
{
 
  // Function to count number of bit
  public static int countBit(int n)
  {
    int Count = 0;
    while (n != 0) {
      n /= 2;
      Count++;
    }
    return Count;
  }
 
  // Function to check
  // if a pair is present or not
  public static boolean checkPair(int arr[], int N)
  {
    int Min = Integer.MAX_VALUE;
    int Max = Integer.MIN_VALUE;
 
    // Find Maximum and Minimum element
    // of the array
    for (int i = 0; i < N; i++) {
      Min = Math.min(Min, arr[i]);
      Max = Math.max(Max, arr[i]);
    }
 
    // Check if max and min element have
    // different count of bits
    // then return 1 else return 0
    if (countBit(Min) != countBit(Max))
      return true;
    else
      return false;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 4, 5, 8, 6 };
    int N = arr.length;
 
    // Function call
    if (checkPair(arr, N) == true)
      System.out.println("Yes");
    else
      System.out.println("No");
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Python code for the above approach
 
# Function to count number of bit
import sys
 
def countBit(n):
 
    Count = 0
    while (n):
        n = n // 2
        Count += 1
     
    return Count
 
# Function to check
# if a pair is present or not
def checkPair(arr,N):
 
    Min = sys.maxsize
    Max = -sys.maxsize -1
 
    # Find Maximum and Minimum element
    # of the array
    for i in range(N):
        Min = min(Min, arr[i])
        Max = max(Max, arr[i])
     
 
    # Check if max and min element have
    # different count of bits
    # then return 1 else return 0
    if (countBit(Min) != countBit(Max)):
        return True
    else:
        return False
 
# Driver Code
 
arr = [ 4, 5, 8, 6 ]
N = len(arr)
 
# Function call
if (checkPair(arr, N)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by shinjanpatra


C#




// C# program to implement
// the above approach
using System;
class GFG
{
  // Function to count number of bit
  public static int countBit(int n)
  {
    int Count = 0;
    while (n != 0) {
      n /= 2;
      Count++;
    }
    return Count;
  }
 
  // Function to check
  // if a pair is present or not
  public static bool checkPair(int[] arr, int N)
  {
    int Minn = Int32.MaxValue;
    int Maxx = Int32.MinValue;
 
    // Find Maximum and Minimum element
    // of the array
    for (int i = 0; i < N; i++) {
      Minn = Math.Min(Minn, arr[i]);
      Maxx = Math.Max(Maxx, arr[i]);
    }
 
    // Check if max and min element have
    // different count of bits
    // then return 1 else return 0
    if (countBit(Minn) != countBit(Maxx))
      return true;
    else
      return false;
  }
 
// Driver Code
public static void Main()
{
    int[] arr = { 4, 5, 8, 6 };
    int N = arr.Length;
 
    // Function call
    if (checkPair(arr, N) == true)
      Console.Write("Yes");
    else
      Console.Write("No");
}
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
// Javascript program for the above approach
 
  // Function to count number of bit
  function countBit(n)
  {
    let Count = 0;
    while (n != 0) {
      n /= 2;
      Count++;
    }
    return Count;
  }
 
  // Function to check
  // if a pair is present or not
  function checkPair(arr, N)
  {
    let Min = Number.MAX_VALUE;
    let Max = Number.MIN_VALUE;
 
    // Find Maximum and Minimum element
    // of the array
    for (let i = 0; i < N; i++) {
      Min = Math.min(Min, arr[i]);
      Max = Math.max(Max, arr[i]);
    }
 
    // Check if max and min element have
    // different count of bits
    // then return 1 else return 0
    if (countBit(Min) != countBit(Max))
      return true;
    else
      return false;
  }
 
// Driver Code
 
    let arr = [ 4, 5, 8, 6 ];
    let N = arr.length;
 
    // Function call
    if (checkPair(arr, N) == true)
      document.write("Yes");
    else
      document.write("No");
 
// This code is contributed by code_hunt.
</script>


Output

Yes

Time Complexity: O(N)
Auxiliary Space: O(1)



Similar Reads

Count pair of nodes with greater Bitwise AND than Bitwise XOR in given Linked List
Given a singly linked list, the task is to Count the pairs of nodes with greater Bitwise AND than Bitwise XOR. Examples: Input: list: 1-&gt;4-&gt;2-&gt;6-&gt;3Output: 2Explanation: 1st List Node Pair: (4, 6 ), Bitwise AND = 4, Bitwise XOR = 22nd List Node Pair: (2, 3), Bitwise AND = 2, Bitwise XOR = 1 Input: list: 17-&gt;34-&gt;62-&gt;46-&gt;30-
13 min read
Count pairs with Bitwise XOR greater than both the elements of the pair
Given an array arr[] of size N, the task is to count the number of pairs whose Bitwise XOR is greater than both the elements in the pair. Examples: Input: arr[] = {2, 4, 3}Output: 2Explanation: There are only 2 pairs whose Bitwise XOR is greater than both the elements in the pair:1) (2, 4): Bitwise XOR = 2 ^ 4 = 6, which is greater than both 2 and
10 min read
Find size of largest subset with bitwise AND greater than their bitwise XOR
Given an array arr[] of N integers, the task is to find the size of the largest subset such that the bitwise AND of all elements of the subset is greater than the bitwise XOR of all elements of the subset. Example: Input: arr[] = {1, 2, 3, 4, 5}Output: 2Explanation: The subset {2, 3} has the bitwise AND of all elements as 2 while the bitwise XOR of
6 min read
Count of pairs with bitwise XOR value greater than its bitwise AND value | Set 2
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bit wise XOR value is greater than bit wise AND value Examples: Input : arr[]={ 12, 4 , 15}Output: 2Explanation: 12 ^ 4 = 8 , 12 &amp; 4 = 4 . so 12 ^ 4 &gt; 12 &amp; 4 4 ^ 15 = 11, 4 &amp; 15 = 4. so 4 ^ 15 &gt; 4 &amp; 15 . So , above two are valid pa
6 min read
Count of pairs with bitwise XOR value greater than its bitwise AND value
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bitwise XOR value is greater than bitwise AND value Examples: Input : arr[]={ 12, 4, 15}Output: 2Explanation: 12 ^ 4 = 8, 12 &amp; 4 = 4. so 12 ^ 4 &gt; 12 &amp; 4 4 ^ 15 = 11, 4 &amp; 15 = 4. so 4 ^ 15 &gt; 4 &amp; 15 . So, above two are valid pairs {
4 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which elements greater than a given number K are more than elements not greater than K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray of length 4 or
10 min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] &gt; B[i] + B[j] and i &lt; j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. The
16 min read
Count pairs having bitwise XOR greater than K from a given array
Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is greater than K. Examples: Input: arr = {1, 2, 3, 5} , K = 2 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions are: arr[0] ^ arr[1] = 1 ^ 2 = 3 arr[0] ^ arr[3
16 min read
Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Given an array arr[] of size N. The task is to find the number of pairs (arr[i], arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs where bitwise AND of least significant bits is 1.cntOR: Count of pairs where bitwise OR of least significant bits is 1.cntXOR: Count of pairs where bitwise XOR of least significant bits is 1. Exampl
7 min read
Construct a sorted Array such that setbit in bitwise XOR of any pair is even
Given an integer N(1 ≤ N ≤ 500), Construct an integer arr[] of length N, such that it should follow all the given conditions below: Each element of arr[] should be distinct.Binary representation of (arr[i]^arr[j]) should contain even number of set bits for all ( 1≤i≤N ) and ( i≠j ).All the elements in arr[] should be in sorted order.Ai &gt; 0 for a
7 min read
Article Tags :
Practice Tags :