Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Bitwise XOR of Bitwise AND of all pairs from two given arrays
Next article icon

Count pairs with bitwise XOR exceeding bitwise AND from a given array

Last Updated : 07 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&) of each pair is less than its bitwise XOR(^).

Examples:

Input: arr[] = {1, 2, 3, 4, 5} 
Output: 8
Explanation: 
Pairs that satisfy the given conditions are: 
(1 & 2) < (1 ^ 2)
(1 & 3) < (1 ^ 3)
(1 & 4) < (1 ^ 4)
(1 & 5) < (1 ^ 5)
(2 & 4) < (2 ^ 4)
(2 & 5) < (2 ^ 5)
(3 & 4) < (3 ^ 4)
(3 & 5) < (3 ^ 5)
Therefore, the required output is 8. 

Input: arr[] = {1, 4, 3, 7, 10} 
Output: 9 

Approach: The simplest approach is to traverse the array and generate all possible pairs from the given array. For each pair, check if its bitwise AND(&) is less than the bitwise XOR(^) of that pair or not. If found to be true, then increment the count of pairs by 1. Finally, print the count of such pairs obtained. 

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

Efficient approach: To optimize the above approach, follow the properties of the bitwise operators:

1 ^ 0 = 1
0 ^ 1 = 1
1 & 1 = 1
X = b31b30…..b1b0
Y = a31b30….a1a0 
If the Expression {(X & Y) > (X ^ Y)} is true then the most significant bit(MSB) of both X and Y must be equal. 
Total count of pairs that satisfy the condition{(X & Y) > (X ^ Y)} are: 

[Tex]\sum_{i=0}^{31}\binom{bit[i]}{2}                      [/Tex]
 bit[i] stores the count of array elements whose position of most significant bit(MSB) is i.

Therefore, total count of pairs that satisfy the given condition{(X & Y) < (X ^ Y)} 
= [{N * (N – 1) /2} – {
[Tex] \sum_{i=0}^{31}\binom{bit[i]}{2}                       [/Tex]
 }]

Follow the steps below to solve the problem: 

  1. Initialize a variable, say res, to store the count of pairs that satisfy the given condition.
  2. Traverse the given array.
  3. Store the position of most significant bit of each element of the given array.
  4. Finally, evaluate the result by the above mentioned formula and print the result.

Below is the implementation of the above approach:

C++

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count pairs that
// satisfy the above condition.
int cntPairs(int arr[], int N)
{
 
    // Stores the count
    // of pairs
    int res = 0;
 
    // Stores the count of array
    // elements having same
    // positions of MSB
    int bit[32] = { 0 };
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores the index of
        // MSB of array elements
        int pos
            = log2(arr[i]);
        bit[pos]++;
    }
 
    // Calculate number of pairs
    for (int i = 0; i < 32; i++) {
        res += (bit[i]
                * (bit[i] - 1))
               / 2;
    }
    res = (N * (N - 1)) / 2 - res;
 
    return res;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntPairs(arr, N);
}
                      
                       

Java

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
 
// Function to count pairs that
// satisfy the above condition.
static int cntPairs(int[] arr, int N)
{
     
    // Stores the count
    // of pairs
    int res = 0;
 
    // Stores the count of array
    // elements having same
    // positions of MSB
    int[] bit = new int[32];
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Stores the index of
        // MSB of array elements
        int pos = (int)(Math.log(arr[i]) /
                        Math.log(2));
        bit[pos]++;
    }
 
    // Calculate number of pairs
    for(int i = 0; i < 32; i++)
    {
        res += (bit[i] * (bit[i] - 1)) / 2;
    }
    res = (N * (N - 1)) / 2 - res;
 
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 3, 4, 5, 6 };
    int N = arr.length;
     
    System.out.println(cntPairs(arr, N));
}
}
 
// This code is contributed by akhilsaini
                      
                       

Python3

# Python3 program to implement
# the above approach
import math
 
# Function to count pairs that
# satisfy the above condition.
def cntPairs(arr, N):
     
    # Stores the count
    # of pairs
    res = 0
     
    # Stores the count of array
    # elements having same
    # positions of MSB
    bit = [0] * 32
     
    # Traverse the array
    for i in range(0, N):
         
        # Stores the index of
        # MSB of array elements
        pos = int(math.log(arr[i], 2))
        bit[pos] = bit[pos] + 1
     
    # Calculate number of pairs
    for i in range(0, 32):
        res = res + int((bit[i] *
                        (bit[i] - 1)) / 2)
                         
    res = int((N * (N - 1)) / 2 - res)
     
    return res
 
# Driver Code
if __name__ == "__main__":
     
    arr = [ 1, 2, 3, 4, 5, 6 ]
    N = len(arr)
     
    print(cntPairs(arr, N))
 
# This code is contributed by akhilsaini
                      
                       

C#

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to count pairs that
// satisfy the above condition.
static int cntPairs(int[] arr, int N)
{
     
    // Stores the count
    // of pairs
    int res = 0;
 
    // Stores the count of array
    // elements having same
    // positions of MSB
    int[] bit = new int[32];
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Stores the index of
        // MSB of array elements
        int pos = (int)(Math.Log(arr[i]) /
                        Math.Log(2));
        bit[pos]++;
    }
 
    // Calculate number of pairs
    for(int i = 0; i < 32; i++)
    {
        res += (bit[i] * (bit[i] - 1)) / 2;
    }
    res = (N * (N - 1)) / 2 - res;
 
    return res;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 3, 4, 5, 6 };
    int N = arr.Length;
     
    Console.Write(cntPairs(arr, N));
}
}
 
// This code is contributed by akhilsaini
                      
                       

Javascript

<script>
 
// Javascript program to implement
// the above approach
 
// Function to count pairs that
// satisfy the above condition.
function cntPairs(arr, N)
{
 
    // Stores the count
    // of pairs
    let res = 0;
 
    // Stores the count of array
    // elements having same
    // positions of MSB
    let bit = new Array(32).fill(0);
 
    // Traverse the array
    for(let i = 0; i < N; i++)
    {
     
        // Stores the index of
        // MSB of array elements
        let pos = parseInt(Math.log(arr[i]) /
                           Math.log(2));;
        bit[pos]++;
    }
 
    // Calculate number of pairs
    for(let i = 0; i < 32; i++)
    {
        res += parseInt((bit[i]
                * (bit[i] - 1)) / 2);
    }
    res = parseInt((N * (N - 1)) / 2) - res;
 
    return res;
}
 
// Driver Code
let arr = [ 1, 2, 3, 4, 5, 6 ];
let N = arr.length;
 
document.write(cntPairs(arr, N));
 
// This code is contributed by subhammahato348.
 
</script>
                      
                       

Output: 
11

 

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

Method 2 : Bitwise and is greater than bitwise xor if and only if most significant bit is equal.

  • Create a bits[] array of size 32 (max no of bits)
  • Initialize ans to 0.
  • We will traverse the array from the start and for each number,
    • Find its most significant bit and say it is j.
    • Add the value stored in bits[j] array to the ans. (for the current element bits[j] number of pairs can be formed)
    • Now increase the value of bits[j] by 1.
  • Now total number of pairs = n*(n-1)/2. Subtract the ans from it.

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
int findCount(int arr[], int N)
{
    // For storing number of pairs
    int ans = 0;
 
    // For storing count of numbers
    int bits[32] = { 0 };
 
    // Iterate from 0 to N - 1
    for (int i = 0; i < N; i++) {
 
        // Find the most significant bit
        int val = log2l(arr[i]);
 
        ans += bits[val];
        bits[val]++;
    }
    return N * (N - 1) / 2 - ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4, 5, 6 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << findCount(arr, N);
 
    return 0;
}
                      
                       

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
static int findCount(int arr[], int N)
{
     
    // For storing number of pairs
    int ans = 0;
 
    // For storing count of numbers
    int bits[] = new int[32];
 
    // Iterate from 0 to N - 1
    for(int i = 0; i < N; i++)
    {
         
        // Find the most significant bit
        int val = (int)(Math.log(arr[i]) /
                        Math.log(2));
 
        ans += bits[val];
        bits[val]++;
    }
    return N * (N - 1) / 2 - ans;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4, 5, 6 };
 
    int N = arr.length;
 
    // Function Call
    System.out.println(findCount(arr, N));
}
}
 
// This code is contributed by Kingash
                      
                       

Python3

# Python3 program for the above approach
import math
def findCount(arr, N):
 
    # For storing number of pairs
    ans = 0
 
    # For storing count of numbers
    bits = [0] * 32
 
    # Iterate from 0 to N - 1
    for i in range(N):
 
        # Find the most significant bit
        val = int(math.log2(arr[i]))
 
        ans += bits[val]
        bits[val] += 1
    return (N * (N - 1) // 2 - ans)
 
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [1, 2, 3, 4, 5, 6]
 
    N = len(arr)
 
    # Function Call
    print(findCount(arr, N))
 
    # This code is contributed by ukasp.
                      
                       

C#

// C# program for the above approach
using System;
 
class GFG{
 
static int findCount(int[] arr, int N)
{
     
    // For storing number of pairs
    int ans = 0;
 
    // For storing count of numbers
    int[] bits = new int[32];
 
    // Iterate from 0 to N - 1
    for(int i = 0; i < N; i++)
    {
         
        // Find the most significant bit
        int val = (int)(Math.Log(arr[i]) /
                        Math.Log(2));
 
        ans += bits[val];
        bits[val]++;
    }
    return N * (N - 1) / 2 - ans;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int[] arr = { 1, 2, 3, 4, 5, 6 };
 
    int N = arr.Length;
 
    // Function Call
    Console.Write(findCount(arr, N));
}
}
 
// This code is contributed by subhammahato348
                      
                       

Javascript

<script>
 
// Javascript program for the above approach
function findCount(arr, N)
{
     
    // For storing number of pairs
    let ans = 0;
 
    // For storing count of numbers
    let bits = new Array(32).fill(0);
 
    // Iterate from 0 to N - 1
    for(let i = 0; i < N; i++)
    {
         
        // Find the most significant bit
        let val = parseInt(Math.log(arr[i]) /
                           Math.log(2));
 
        ans += bits[val];
        bits[val]++;
    }
    return parseInt(N * (N - 1) / 2) - ans;
}
 
// Driver Code
 
// Given array arr[]
let arr = [ 1, 2, 3, 4, 5, 6 ];
 
let N = arr.length;
 
// Function Call
document.write(findCount(arr, N));
 
// This code is contributed by subhammahato348
 
</script>
                      
                       

Output
11

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



Next Article
Bitwise XOR of Bitwise AND of all pairs from two given arrays

R

RaghavRathi2
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • Competitive Programming
  • DSA
  • Mathematical
  • Bitwise-AND
  • Bitwise-XOR
Practice Tags :
  • Arrays
  • Bit Magic
  • Mathematical

Similar Reads

  • Bitwise XOR of Bitwise AND of all pairs from two given arrays
    Given two arrays arr1[] and arr2[] consisting of N and M integers respectively, the task is to print the Bitwise XOR of Bitwise AND of all pairs possible by selecting an element from arr1[] and arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {6, 5}Output: 0Explanation: Bitwise AND of the pair
    10 min read
  • Count pairs from an array whose Bitwise OR is greater than Bitwise AND
    Given an array A[] consisting of N integers, the task is to count the number of pairs (i, j) such that i < j, and Bitwise OR of A[i] and A[j] is greater than Bitwise AND of A[i] and A[j]. Examples: Input: A[] = {1, 4, 7}Output: 3Explanation: There are 3 such pairs: (1, 4), (4, 7), (1, 7).1) 1 | 4
    10 min read
  • Check if any Array pair has bitwise XOR greater than bitwise AND
    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 oper
    9 min read
  • Find XOR sum of Bitwise AND of all pairs from given two Arrays
    Given two arrays A and B of sizes N and M respectively, the task is to calculate the XOR sum of bitwise ANDs of all pairs of A and B Examples: Input: A={3, 5}, B={2, 3}, N=2, M=2Output:0Explanation:The answer is (3&2)^(3&3)^(5&2)^(5&3)=1^3^0^2=0. Input: A={1, 2, 3}, B={5, 6}, N=3, M=
    9 min read
  • Count Number of Pairs where Bitwise AND and Bitwise XOR is Equal
    Given an integer array arr of size N, the task is to count the number of pairs whose BITWISE AND and BITWISE XOR are equal. Example: Input: N = 3, arr[] = {0,0,1}Output: 1Explanation: There is only one pair arr[0] and arr[1] as 0&0=0 and 0^0=0 Input: N = 4, arr[] = {1, 2, 4, 8}Output: 0Explanati
    4 min read
  • Count pairs from given array with Bitwise OR equal to K
    Given an array arr[] consisting of N positive integers and an integer K, the task is to count all pairs possible from the given array with Bitwise OR equal to K. Examples: Input: arr[] = {2, 38, 44, 29, 62}, K = 46Output: 2Explanation: Only the following two pairs are present in the array whose Bitw
    5 min read
  • Count pairs with equal Bitwise AND and Bitwise OR value
    Given an array, arr[] of size N, the task is to count the number of unordered pairs such that Bitwise AND and Bitwise OR of each pair is equal. Examples: Input: arr[] = {1, 2, 1} Output: 1 Explanation: Bitwise AND value and Bitwise OR value all possible pairs are: Bitwise AND of the pair(arr[0], arr
    6 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 conditio
    15+ min read
  • Count pairs with Bitwise XOR as EVEN number
    Given an array of N integers, the task is to find the number of pairs (i, j) such that A[i] ^ A[j] is even. Examples: Input: A[] = { 5, 4, 7, 2, 1} Output: 4 Since pair of A[] = ( 5, 4 ) = 1( 5, 7 ) = 2( 5, 2 ) = 7( 5, 1 ) = 4 ( 4, 7 ) = 3( 4, 2 ) = 6( 4, 1 ) = 5 ( 7, 2 ) = 5( 7, 1 ) = 6 ( 2, 1 ) =
    11 min read
  • Count pairs with Bitwise-AND as even number
    Given an array of [Tex]N [/Tex]integers. The task is to find the number of pairs (i, j) such that A[i] & A[j] is even. Examples: Input: N = 4, A[] = { 5, 1, 3, 2 } Output: 3 Since pair of A[] are: ( 5, 1 ), ( 5, 3 ), ( 5, 2 ), ( 1, 3 ), ( 1, 2 ), ( 3, 2 ) 5 AND 1 = 1, 5 AND 3 = 1, 5 AND 2 = 0, 1
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences