Print distinct absolute differences of all possible pairs from a given array
Last Updated :
19 Jul, 2024
Given an array, arr[] of size N, the task is to find the distinct absolute differences of all possible pairs of the given array.
Examples:
Input: arr[] = { 1, 3, 6 }
Output: 2 3 5
Explanation:
abs(arr[0] - arr[1]) = 2
abs(arr[1] - arr[2]) = 3
abs(arr[0] - arr[2]) = 5
Input: arr[] = { 5, 6, 7, 8, 14, 19, 21, 22 }
Output: 1 2 3 5 6 7 8 9 11 12 13 14 15 16 17
Naive Approach: The simplest approach to solve this problem is to generate all possible pairs of the given array and insert the absolute difference of each pair in a Set. Finally, print all the elements of the set.
C++
// C++ implementation to find all
// Pairs possible from the given Array
#include <bits/stdc++.h>
using namespace std;
// Function to print all possible
// pairs from the array
void printPairs(int arr[], int n)
{
unordered_set<int> s;
// Nested loop for all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
s.insert(abs(arr[i] - arr[j]));
}
}
for (auto x : s)
cout << x << " ";
}
// Driver code
int main()
{
int arr[] = { 1, 3, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
printPairs(arr, n);
return 0;
}
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Note that the above approach does not produce output in sorted order. If we wish to get items in sorted order, we can use set in C++, TreeSet in Java or Sort the set items in Python. Please note that the time complexity will increase to N^2 Log N in that case.
Another Approach (Efficient for Small Range Elements): The above approach can be optimized using Bitset. Follow the steps below to solve the problem:
- Initialize a Bitset, say bset, where bset[i] check if i is present in the array or not.
- Traverse the array arr[] and store all the array elements in the bset.
- Initialize a Bitset, say diff, where diff[i] stores if the absolute difference of there exists any pair in the array whose value equal to i or not.
- Find the largest element of the array, say Max
- Iterate over the range [0, Max]. In every ith iteration check if bset[i] is true or not. If found to be true, then insert the absolute difference of i with all other array elements using diff = diff | (bset >> i).
- Finally, iterate over the range [0, Max] and check if diff[i] is true or not. If found to be true, then print i.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define Max 100005
// Function to find all distinct
// absolute difference of all
// possible pairs of the array
void printUniqDif(int n, int a[])
{
// bset[i]: Check if i is present
// in the array or not
bitset<Max> bset;
// diff[i]: Check if there exists a
// pair whose absolute difference is i
bitset<Max> diff;
// Traverse the array, arr[]
for (int i = 0; i < n; i++) {
// Add in bitset
bset.set(a[i]);
}
// Iterate over the range[0, Max]
for (int i = 0; i <= Max; i++) {
// If i-th bit is set
if (bset[i]) {
// Insert the absolute difference
// of all possible pairs whose
// first element is arr[i]
diff = diff | (bset >> i);
}
}
// Stores count of set bits
int X = bset.count();
// If there is at least one
// duplicate element in arr[]
if (X != n) {
cout << 0 << " ";
}
// Printing the distinct absolute
// differences of all possible pairs
for (int i = 1; i <= Max; i++) {
// If i-th bit is set
if (diff[i]) {
cout << i << " ";
}
}
}
// Driver Code
int main()
{
// Given array
int a[] = { 1, 4, 6 };
// Given size
int n = sizeof(a) / sizeof(a[0]);
// Function Call
printUniqDif(n, a);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
static int Max = 100005;
// Function to find all distinct
// absolute difference of all
// possible pairs of the array
static void printUniqDif(int n, int[] a)
{
// bset[i] Check if i is present
// in the array or not
int[] bset = new int[33];
// diff[i] Check if there exists a
// pair whose absolute difference is i
int diff = 0;
// Traverse the array, arr[]
for (var i = 0; i < n; i++)
bset[a[i]] = 1;
// Iterate over the range[0, Max]
int d = 0;
for (var i = 0; i < 33; i++)
d = d | (bset[i] << i);
for (var i = 0; i < 33; i++)
{
// If i-th bit is set
if (bset[i] == 1)
// Insert the absolute difference
// of all possible pairs whose
// first element is arr[i]
diff |= (d >> i);
}
// Stores count of set bits
int X = 0;
for (int i = 0; i < 33; i++)
if (bset[i] == 1)
X++;
String Y =Integer.toBinaryString(diff);
// If there is at least one
// duplicate element in arr[]
if (X != n)
System.out.print("0 ");
// Printing the distinct absolute
// differences of all possible pairs
for (var i = 1; i < Y.length(); i++)
{
// If i-th bit is set
if (Y.charAt(i) == '1')
System.out.print(i + " ");
}
}
// Driver Code
public static void main(String[] args)
{
// Given array
int[] a = {1, 4, 6};
// Given size
int n = a.length;
// Function Call
printUniqDif(n, a);
}
}
// This code is contributed by phasing17
Python
# Python3 program for the above approach
Max = 100005
# Function to find all distinct
# absolute difference of all
# possible pairs of the array
def printUniqDif(n, a):
# bset[i]: Check if i is present
# in the array or not
bset = [0 for i in range(33)]
# diff[i]: Check if there exists a
# pair whose absolute difference is i
diff = 0
# Traverse the array, arr[]
for i in range(n):
bset[a[i]] = 1
# Iterate over the range[0, Max]
d = 0
for i in range(1,33):
d = d | (bset[i]<<i)
for i in range(33):
# If i-th bit is set
if (bset[i]):
# Insert the absolute difference
# of all possible pairs whose
# first element is arr[i]
diff = diff | d >> i
# print(bin(diff))
# Stores count of set bits
X, Y = bset.count(1), str(bin(diff)[2:])
# If there is at least one
# duplicate element in arr[]
if (X != n):
print(0, end=" ")
# Printing the distinct absolute
# differences of all possible pairs
for i in range(1, len(Y)):
# If i-th bit is set
if (Y[i] == '1'):
print(i, end = " ")
# Driver Code
if __name__ == '__main__':
# Given array
a = [1, 4, 6]
# Given size
n = len(a)
# Function Call
printUniqDif(n, a)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static int Max = 100005;
// Function to find all distinct
// absolute difference of all
// possible pairs of the array
static void printUniqDif(int n, int[] a)
{
// bset[i] Check if i is present
// in the array or not
int[] bset = new int[33];
// diff[i] Check if there exists a
// pair whose absolute difference is i
int diff = 0;
// Traverse the array, arr[]
for (var i = 0; i < n; i++)
bset[a[i]] = 1;
// Iterate over the range[0, Max]
int d = 0;
for (var i = 0; i < 33; i++)
d = d | (bset[i] << i);
for (var i = 0; i < 33; i++)
{
// If i-th bit is set
if (bset[i] == 1)
// Insert the absolute difference
// of all possible pairs whose
// first element is arr[i]
diff |= (d >> i);
}
// Stores count of set bits
int X = bset.Count(f => f == 1);
string Y = Convert.ToString(diff, 2);
// If there is at least one
// duplicate element in arr[]
if (X != n)
Console.Write("0 ");
// Printing the distinct absolute
// differences of all possible pairs
for (var i = 1; i < Y.Length; i++)
{
// If i-th bit is set
if (Y[i] == '1')
Console.Write(i + " ");
}
}
// Driver Code
public static void Main(string[] args)
{
// Given array
int[] a = {1, 4, 6};
// Given size
int n = a.Length;
// Function Call
printUniqDif(n, a);
}
}
// This code is contributed by phasing17
JavaScript
// JS program for the above approach
let Max = 100005
// Function to find all distinct
// absolute difference of all
// possible pairs of the array
function printUniqDif(n, a)
{
// bset[i] Check if i is present
// in the array or not
let bset = new Array(33).fill(0)
// diff[i] Check if there exists a
// pair whose absolute difference is i
let diff = 0
// Traverse the array, arr[]
for (var i = 0; i < n; i++)
bset[a[i]] = 1
// Iterate over the range[0, Max]
let d = 0
for (var i = 0; i < 33; i++)
d = d | (bset[i] << i)
for (var i = 0; i < 33; i++)
{
// If i-th bit is set
if (bset[i] == 1)
// Insert the absolute difference
// of all possible pairs whose
// first element is arr[i]
diff |= (d >> i)
}
// Stores count of set bits
let X = bset.filter(x => x == 1).length
let Y = diff.toString(2)
// If there is at least one
// duplicate element in arr[]
if (X != n)
process.stdout.write("0 ")
// Printing the distinct absolute
// differences of all possible pairs
for (var i = 1; i < Y.length; i++)
// If i-th bit is set
if (Y.charAt(i) == '1')
process.stdout.write(i + " ")
}
// Driver Code
// Given array
let a = [1, 4, 6]
// Given size
let n = a.length
// Function Call
printUniqDif(n, a)
// This code is contributed by phasing17
Time Complexity:O(N + Max), where Max is the largest element of the array.
Auxiliary Space: O(Max)
Similar Reads
Sort an array according to absolute difference with given value using Functors Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., the element having a minimum difference comes first and so on. Note: If two or more elements are at equal distance arrange them in same sequence as in the given array. Exa
6 min read
Absolute difference of all pairwise consecutive elements in a Set Given a set of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements in a set. Pairwise consecutive pairs of a set of size N are accessed using iterator. Example: Input: s = {8, 5, 4, 3, 15, 20} Output: 1 1 3 7 5 Explanation: The set is : 3
5 min read
Count pairs from an array with absolute difference not less than the minimum element in the pair Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (arr[i], arr[j]) such that absolute difference between the two elements is at least equal to the minimum element in the pair. Examples: Input: arr[] = {1, 2, 2, 3}Output: 3Explanation:Following are the pa
14 min read
Sort array such that absolute difference of adjacent elements is in increasing order Given an unsorted array of length N. The task is to sort the array, such that abs(a[i]-a[i+1]) < = abs(a[i+1]-a[i+2]) for all 0 < = i< N that is abs(a[0]-a[1]) < = abs(a[1]-a[2]) < = abs(a[2]-a[3]) and so on.Examples: Input: arr[] = {7, 4, 9, 9, -1, 9}Output: {9, 7, 9, 4, 9, -1}Explan
7 min read
Sum of absolute differences of indices of occurrences of each array element Given an array arr[] consisting of N integers, the task for each array element arr[i] is to print the sum of |i - j| for all possible indices j such that arr[i] = arr[j]. Examples: Input: arr[] = {1, 3, 1, 1, 2}Output: 5 0 3 4 0Explanation: For arr[0], sum = |0 - 0| + |0 - 2| + |0 - 3| = 5. For arr[
10 min read
C++ Program to Find a pair with the given difference Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
4 min read
Find k ordered pairs in array with minimum difference d Given an array arr[] and two integers K and D, the task is to find exactly K pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? D and i != j. If it is impossible to get such pairs then print -1. Note that a single element can only participate in a single pair.Examples: Input: arr[]
6 min read
Count ways to construct array with even product from given array such that absolute difference of same indexed elements is at most 1 Given an array A[] of size N, the task is to count the numbers of ways to construct an array B[] of size N, such that the absolute difference at the same indexed elements must be less than or equal to 1, i.e. abs(A[i] - B[i]) ? 1, and the product of elements of the array B[] must be an even number.
6 min read
Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum Given an array arr[] of some positive integers and missing occurrence of a specific integer represented by -1, the task is to find that missing number such that maximum absolute difference between adjacent elements is minimum.Examples: Input: arr[] = {-1, 10, -1, 12, -1} Output: 11 Explanation: Diff
6 min read
Split squares of first N natural numbers into two sets with minimum absolute difference of their sums Given an integer N, the task is to partition the squares of first N( always a multiple of 8 ) natural numbers into two sets such that the difference of their subset sums is minimized. Print both the subsets as the required answer. Examples: Input: N = 8Output:01 16 36 494 9 25 64Explanation: Squares
9 min read