Pairs from an array that satisfy the given condition
Last Updated :
21 Feb, 2023
Given an array arr[], the task is to count all the valid pairs from the array. A pair (arr[i], arr[j]) is said to be valid if func( arr[i] ) + func( arr[j] ) = func( XOR(arr[i], arr[j]) ) where func(x) returns the number of set bits in x.
Examples:
Input: arr[] = {2, 3, 4, 5, 6}
Output: 3
(2, 4), (2, 5) and (3, 4) are the only valid pairs.
Input: arr[] = {12, 13, 34, 25, 6}
Output: 4
Approach: Iterating every possible pair and check whether the pair satisfies the given condition. If the condition is satisfied then update count = count + 1. Print the count in the end.
Algorithm:
1. The setBits function takes an integer n as input and returns the number of set bits (i.e., bits with a value of 1) in its binary representation. It does this by initializing a variable count to 0 and then repeatedly performing the following steps as long as n is not 0:
a. Subtracting 1 from n and performing a bitwise AND operation with the original value of n.
b. Incrementing count by 1.
2. The idea behind this function is that each iteration of the loop removes the rightmost set bit in n, so the loop will continue until all set bits have been removed, and the number of iterations (i.e., the value of count) will be equal to the number of set bits in n.
3. The countPairs function takes an array a of integers and its length n as input, and returns the number of pairs of elements in the array that satisfy a certain condition. It does this by initializing a variable count to 0 and then iterating over all pairs of elements in the array, checking if the condition is satisfied for each pair:
a. For each pair of elements, it calls the setBits function to compute the number of set bits in each element, and the number of set bits in the XOR of the two elements.
b. It then checks if the sum of the number of set bits in the two elements is equal to the number of set bits in their XOR.
c. If the condition is satisfied, it increments count by 1.
4. The setBits function is used in the countPairs function to compute the number of set bits in integers. It does this by repeatedly removing the rightmost set bit in the input integer until all set bits have been removed, and counting the number of times this operation is performed.
5. The countPairs function uses two nested loops to iterate over all pairs of elements in the array, and computes the number of set bits in each element and in their XOR using the setBits function. It then checks if the sum of the number of set bits in the two elements is equal to the number of set bits in their XOR. If the condition is satisfied, it increments the count of pairs.
6. The function returns the total count of pairs that satisfy the condition.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the number
// of set bits in n
int setBits(int n)
{
int count = 0;
while (n) {
n = n & (n - 1);
count++;
}
return count;
}
// Function to return the count of required pairs
int countPairs(int a[], int n)
{
int count = 0;
for (int i = 0; i < n - 1; i++) {
// Set bits for first element of the pair
int setbits_x = setBits(a[i]);
for (int j = i + 1; j < n; j++) {
// Set bits for second element of the pair
int setbits_y = setBits(a[j]);
// Set bits of the resultant number which is
// the XOR of both the elements of the pair
int setbits_xor_xy = setBits(a[i] ^ a[j]);
// If the condition is satisfied
if (setbits_x + setbits_y == setbits_xor_xy)
// Increment the count
count++;
}
}
// Return the total count
return count;
}
// Driver code
int main()
{
int a[] = { 2, 3, 4, 5, 6 };
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n);
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Function to return the number
// of set bits in n
static int setBits(int n)
{
int count = 0;
while (n > 0)
{
n = n & (n - 1);
count++;
}
return count;
}
// Function to return the count of
// required pairs
static int countPairs(int a[], int n)
{
int count = 0;
for (int i = 0; i < n - 1; i++)
{
// Set bits for first element
// of the pair
int setbits_x = setBits(a[i]);
for (int j = i + 1; j < n; j++)
{
// Set bits for second element
// of the pair
int setbits_y = setBits(a[j]);
// Set bits of the resultant number which is
// the XOR of both the elements of the pair
int setbits_xor_xy = setBits(a[i] ^ a[j]);
// If the condition is satisfied
if (setbits_x + setbits_y == setbits_xor_xy)
// Increment the count
count++;
}
}
// Return the total count
return count;
}
// Driver code
public static void main (String[] args)
{
int []a = { 2, 3, 4, 5, 6 };
int n = a.length;
System.out.println(countPairs(a, n));
}
}
// This code is contributed by ajit.
Python3
# Python 3 implementation of the approach
# Function to return the number
# of set bits in n
def setBits(n):
count = 0
while (n):
n = n & (n - 1)
count += 1
return count
# Function to return the count
# of required pairs
def countPairs(a, n):
count = 0
for i in range(0, n - 1, 1):
# Set bits for first element
# of the pair
setbits_x = setBits(a[i])
for j in range(i + 1, n, 1):
# Set bits for second element
# of the pair
setbits_y = setBits(a[j])
# Set bits of the resultant number
# which is the XOR of both the
# elements of the pair
setbits_xor_xy = setBits(a[i] ^ a[j]);
# If the condition is satisfied
if (setbits_x +
setbits_y == setbits_xor_xy):
# Increment the count
count += 1
# Return the total count
return count
# Driver code
if __name__ == '__main__':
a = [2, 3, 4, 5, 6]
n = len(a)
print(countPairs(a, n))
# This code is contributed by
# Sanjit_Prasad
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the number
// of set bits in n
static int setBits(int n)
{
int count = 0;
while (n > 0)
{
n = n & (n - 1);
count++;
}
return count;
}
// Function to return the count of
// required pairs
static int countPairs(int []a, int n)
{
int count = 0;
for (int i = 0; i < n - 1; i++)
{
// Set bits for first element
// of the pair
int setbits_x = setBits(a[i]);
for (int j = i + 1; j < n; j++)
{
// Set bits for second element
// of the pair
int setbits_y = setBits(a[j]);
// Set bits of the resultant number which is
// the XOR of both the elements of the pair
int setbits_xor_xy = setBits(a[i] ^ a[j]);
// If the condition is satisfied
if (setbits_x + setbits_y == setbits_xor_xy)
// Increment the count
count++;
}
}
// Return the total count
return count;
}
// Driver code
public static void Main()
{
int []a = { 2, 3, 4, 5, 6 };
int n = a.Length;
Console.Write(countPairs(a, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
<?php
// PHP implementation of the approach
// Function to return the number
// of set bits in n
function setBits($n)
{
$count = 0;
while ($n)
{
$n = $n & ($n - 1);
$count++;
}
return $count;
}
// Function to return the count of
// required pairs
function countPairs(&$a, $n)
{
$count = 0;
for ($i = 0; $i < $n - 1; $i++)
{
// Set bits for first element
// of the pair
$setbits_x = setBits($a[$i]);
for ($j = $i + 1; $j < $n; $j++)
{
// Set bits for second element of the pair
$setbits_y = setBits($a[$j]);
// Set bits of the resultant number which is
// the XOR of both the elements of the pair
$setbits_xor_xy = setBits($a[$i] ^ $a[$j]);
// If the condition is satisfied
if ($setbits_x +
$setbits_y == $setbits_xor_xy)
// Increment the count
$count++;
}
}
// Return the total count
return $count;
}
// Driver code
$a = array(2, 3, 4, 5, 6 );
$n = sizeof($a) / sizeof($a[0]);
echo countPairs($a, $n);
// This code is contributed by ita_c
?>
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the number
// of set bits in n
function setBits(n)
{
let count = 0;
while (n > 0)
{
n = n & (n - 1);
count++;
}
return count;
}
// Function to return the count of
// required pairs
function countPairs(a, n)
{
let count = 0;
for(let i = 0; i < n - 1; i++)
{
// Set bits for first element
// of the pair
let setbits_x = setBits(a[i]);
for(let j = i + 1; j < n; j++)
{
// Set bits for second element
// of the pair
let setbits_y = setBits(a[j]);
// Set bits of the resultant number which is
// the XOR of both the elements of the pair
let setbits_xor_xy = setBits(a[i] ^ a[j]);
// If the condition is satisfied
if (setbits_x + setbits_y == setbits_xor_xy)
// Increment the count
count++;
}
}
// Return the total count
return count;
}
// Driver code
let a = [ 2, 3, 4, 5, 6 ];
let n = a.length;
document.write(countPairs(a, n));
// This code is contributed by unknown2108
</script>
Complexity Analysis:
- Time Complexity: O(N2logM), where N is the size of the given array and M is the maximum element in the array.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.
Similar Reads
Find an array of size N that satisfies the given conditions
Given three integers N, S, and K, the task is to create an array of N positive integers such that the bitwise OR of any two consecutive elements from the array is odd and there are exactly K subarrays with a sum equal to S where 1 ? K ? N / 2. Examples: Input: N = 4, K = 2, S = 6 Output: 6 7 6 7 Her
8 min read
Count valid pairs in the array satisfying given conditions
Given an array of integers arr[], the task is to count the number of valid pairs of elements from arr. A pair (arr[x], arr[y]) is said to be invalid if arr[x] < arr[y]abs(arr[x] - arr[y]) is odd Note: Pairs (arr[x], arr[y]) and (arr[y], arr[x]) are two different pairs when x != y and the value of
5 min read
Counting pairs in an Array with given condition
Given an array arr[] of integers of size n where n is even, the task is to calculate the number of pairs (i, j), where a pair is counted if( 0 ⤠i < n/2, n/2 ⤠j < n, arr[i] ⥠5*arr[j] ) these relations are fulfilled. Note: 0-based indexing is used and n is even. Examples: Input: n = 4, arr[]
5 min read
Find all Pairs possible from the given Array
Given an array arr[] of N integers, the task is to find all the pairs possible from the given array. Note: (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.Examples: Input: arr[] = {1, 2} Output: (1, 1), (1, 2), (2, 1), (
4 min read
Count index pairs which satisfy the given condition
Given a permutation P of first N natural numbers, the task is to count the index pairs (i, j) such that P[i] + P[j] = max(P[x]) where i ? x ? j.Examples: Input: P[] = {3, 4, 1, 5, 2} Output: 2 Only valid index pairs are (0, 4) and (0, 2)Input: P[] = {1, 3, 2} Output: 1 Naive approach: We can solve t
8 min read
Find maximum value of Indices of Array that satisfy the given conditions
Given an integer N (N ? 5) Then assume you have two infinite arrays X and Y where X[] is an array of element N and each element of Y[] is 2i where i is the index of the array, the task is to find two indices let's say A and B which are the maximum value of the index at which the prefix sum in X[] is
9 min read
Count number of coordinates from an array satisfying the given conditions
Given an array arr[] consisting of N coordinates in the Cartesian Plane, the task is to find the number of coordinates, such as (X, Y), that satisfies all the following conditions: All possible arr[i][0] must be less than X and arr[i][1] must be equal to Y.All possible arr[i][0] must be greater than
10 min read
Generate an array B[] from the given array A[] which satisfies the given conditions
Given an array A[] of N integers such that A[0] + A[1] + A[2] + ... A[N - 1] = 0. The task is to generate an array B[] such that B[i] is either ?A[i] / 2? or ?A[i] / 2? for all valid i and B[0] + B[1] + B[2] + ... + B[N - 1] = 0. Examples: Input: A[] = {1, 2, -5, 3, -1} Output: 0 1 -2 1 0Input: A[]
6 min read
Check if there exist 4 indices in the array satisfying the given condition
Given an array A[] of N positive integers and 3 integers X, Y, and Z, the task is to check if there exist 4 indices (say p, q, r, s) such that the following conditions are satisfied: 0 < p < q < r < s < NSum of the subarray from A[p] to A[q - 1] is XSum of the subarray from A[q] to A[
8 min read
Generate an array of size K which satisfies the given conditions
Given two integers N and K, the task is to generate an array arr[] of length K such that: arr[0] + arr[1] + ... + arr[K - 1] = N.arr[i] > 0 for 0 ? i < K.arr[i] < arr[i + 1] ? 2 * arr[i] for 0 ? i < K - 1. If there are multiple answers find any one of them, otherwise, print -1. Examples:
8 min read