Count pairs with bitwise OR less than Max
Last Updated :
16 Nov, 2022
Given an array arr[] of N integers, the task is to count the pairs of indices (i, j) such that 0 ? i < j ? N and arr[i] | arr[j] ? max(arr[i], arr[j]) where | is the bitwise OR.
Examples:
Input: arr[] = {1, 2, 3}
Output: 2
(1, 3) and (2, 3) are the only valid pairs.
Input: arr[] = {11, 45, 12, 14, 5}
Output: 3
Approach: Run two nested loops and check for every possible pair. If arr[i] | arr[j] <= max(arr[i], arr[j]) then increment the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countPairs( int arr[], int n)
{
int cnt = 0;
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++)
if ((arr[i] | arr[j]) <= max(arr[i], arr[j]))
cnt++;
return cnt;
}
int main()
{
int arr[] = { 1, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countPairs(arr, n);
return 0;
}
|
Java
class GFG
{
static int countPairs( int arr[], int n)
{
int cnt = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
for ( int j = i + 1 ; j < n; j++)
if ((arr[i] | arr[j]) <= Math.max(arr[i], arr[j]))
cnt++;
return cnt;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 };
int n = arr.length;
System.out.println(countPairs(arr, n));
}
}
|
Python3
def countPairs(arr, n):
cnt = 0
for i in range (n - 1 ):
for j in range (i + 1 , n, 1 ):
if ((arr[i] | arr[j]) < = max (arr[i],
arr[j])):
cnt + = 1
return cnt
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 ]
n = len (arr)
print (countPairs(arr, n))
|
C#
using System;
class GFG
{
static int countPairs( int []arr, int n)
{
int cnt = 0;
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++)
if ((arr[i] | arr[j]) <= Math.Max(arr[i], arr[j]))
cnt++;
return cnt;
}
static void Main()
{
int []arr = { 1, 2, 3 };
int n = arr.Length;
Console.WriteLine(countPairs(arr, n));
}
}
|
PHP
<?php
function countPairs( $arr , $n )
{
$cnt = 0;
for ( $i = 0; $i < $n - 1; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
if (( $arr [ $i ] |
$arr [ $j ]) <= max( $arr [ $i ],
$arr [ $j ]))
$cnt ++;
return $cnt ;
}
$arr = array (1, 2, 3);
$n = sizeof( $arr );
echo countPairs( $arr , $n );
?>
|
Javascript
<script>
function countPairs(arr, n) {
let cnt = 0;
for (let i = 0; i < n - 1; i++)
for (let j = i + 1; j < n; j++)
if ((arr[i] | arr[j]) <= Math.max(arr[i], arr[j]))
cnt++;
return cnt;
}
let arr = [1, 2, 3];
let n = arr.length;
document.write(countPairs(arr, n));
</script>
|
Time Complexity: O(n2), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...