Given an array arr[] and a number K, the task is to count the number of pairs whose difference is less than or equal to the K, such that an element can only be considered in only one pair.
Examples:
Input: arr[] = {1, 3, 3, 9, 4}, K = 2
Output: 2
Explanation:
There are only two pairs whose difference is atmost 2
(1, 3), (3, 4)Input: arr[] = {1, 4, 3, 7, 5}, K = 2
Output: 2
Explanation:
There are five pairs in the array whose difference is atmost 2,
(1, 3), (3, 4), (4, 5), (3, 5), (5, 7)
But only two of them can be considered at a time because one element
can be taken in a pair only once.
Approach:
We can iterate over all pairs of elements in the array and count the number of pairs whose difference is less than or equal to K and the elements are not used in any previous pair.
- Initialize a variable count to 0 to keep track of the number of pairs whose difference is less than or equal to K.
- Initialize a boolean array used of size n, where n is the size of the input array. The purpose of this array is to keep track of the elements that have already been used in a pair.
- Use two nested loops to iterate over all pairs of elements in the array. The outer loop runs from 0 to n-1, and the inner loop runs from i+1 to n-1.
- For each pair of elements (arr[i] and arr[j]), check if both elements are unused (!used[i] && !used[j]).
- If both elements are unused, check if the absolute difference between them is less than or equal to K (abs(arr[i]-arr[j]) <= k).
- If the difference is less than or equal to K, increment the count variable, and mark both elements as used (used[i] = true; used[j] = true).
- return the count variable.
Below is the implementation of the approach:
C++
// C++ implementation to count the // number of pairs whose difference // is atmost K in an array #include <iostream> #include<bits/stdc++.h> using namespace std; // Function to count the // number of pairs whose difference // is atmost K in an array int countPairs( int arr[], int k, int n) { int count = 0; bool used[n] = { false }; // to keep track of used elements for ( int i = 0; i < n; i++) { for ( int j = i+1; j < n; j++) { if (!used[i] && !used[j] && abs (arr[i]-arr[j]) <= k) { count++; used[i] = true ; used[j] = true ; } } } return count; } // Driver Code int main() { int arr[] = {1, 3, 3, 9, 4} ; int k = 2; int n = sizeof (arr)/ sizeof (arr[0]); // Function Call int count = countPairs(arr, k,n) ; cout << count << endl;; } |
Java
import java.util.*; public class Main { // Function to count the number of pairs whose // difference is at most K in an array static int countPairs( int [] arr, int k) { int count = 0 ; boolean [] used = new boolean [arr.length]; // to keep track of // used elements for ( int i = 0 ; i < arr.length; i++) { for ( int j = i + 1 ; j < arr.length; j++) { if (!used[i] && !used[j] && Math.abs(arr[i] - arr[j]) <= k) { count++; used[i] = true ; used[j] = true ; } } } return count; } // Driver Code public static void main(String[] args) { int [] arr = { 1 , 3 , 3 , 9 , 4 }; int k = 2 ; // Function Call int count = countPairs(arr, k); System.out.println(count); } } |
C#
using System; class GFG { // Function to count the number of pairs whose // difference is at most K in an array static int CountPairs( int [] arr, int k) { int count = 0; bool [] used = new bool [arr.Length]; // to keep track of used // elements for ( int i = 0; i < arr.Length; i++) { for ( int j = i + 1; j < arr.Length; j++) { if (!used[i] && !used[j] && Math.Abs(arr[i] - arr[j]) <= k) { count++; used[i] = true ; used[j] = true ; } } } return count; } // Driver Code public static void Main( string [] args) { int [] arr = { 1, 3, 3, 9, 4 }; int k = 2; // Function Call int count = CountPairs(arr, k); Console.WriteLine(count); } } |
Output: 2
Time Complexity: O(n^2), since we iterate over all pairs of elements in the array.
Space Complexity: O(n), because we use a boolean array used of size n to keep track of the elements that have already been used in a pair.
Approach:
The idea is to sort the array and find the difference of the adjacent elements, If the difference is at most K, then the pair is considered and the count is increased and then, as per the condition, any element can be in only one pair, then if a pair is found, the increment the counter by 2 such that any element is present in only one pair.
For Example:
Given Array - {1, 4, 3, 7, 5}, K = 2
After Sorting Array will be - {1, 3, 4, 5, 7}
Step 1 - i = 0, count = 0
Consider the pair of elements for i and i + 1
Pair - (1, 3), Difference = 3 - 1 = 2
As the Difference is less than equal to 2
count = 1 and i = 2
Step 2 - i = 2, count = 1
Consider the pair of elements for i and i + 1
Pair - (4, 5), Difference = 5 - 4 = 1
As the Difference is less than equal to 2
count = 2 and i = 4
As i is greater than length-2,
there will be no more possible pairs.
Algorithm:
- Sort the array using any sorting algorithm such that consecutive elements are together.
- Initialize the index counter (say i) to zero and run a while loop till the index counter is less than (length – 1)
- Check the difference of the elements at index i and i + 1.
- If the difference is less than or equal to K increment the index by 2 and also increment the counter by 1 to consider increase the elements increase at once.
- Else, increment the index by 1 to consider the pair formed by the next element.
Below is the implementation of the above approach:
C++
// C++ implementation to count the // number of pairs whose difference // is atmost K in an array #include <iostream> #include<bits/stdc++.h> using namespace std; // Function to count the // number of pairs whose difference // is atmost K in an array int countPairs( int arr[], int k, int n) { // Variable to store the count of pairs // whose difference is atmost K int pair = 0; int index = 0; //int n = sizeof(arr)/sizeof(arr[0]); // Sorting the Array sort(arr,arr + n) ; // Loop to consider the consecutive // pairs of the array while (index < n -1) { // if Pair found increment // the index by 2 if (arr[index + 1] - arr[index] <= k){ pair += 1 ; index += 2 ; } else { index += 1; } } return pair ; } // Driver Code int main() { int arr[] = {1, 4, 3, 7, 5} ; int k = 2; int n = sizeof (arr)/ sizeof (arr[0]); // Function Call int count = countPairs(arr, k,n) ; cout << count << endl;; } // This code is contributed by AnkitRai01 |
Java
// Java implementation to count the // number of pairs whose difference // is atmost K in an array import java.util.*; class GFG { // Function to count the // number of pairs whose difference // is atmost K in an array static int countPairs( int arr[], int k) { // Sorting the Array Arrays.sort(arr) ; // Variable to store the count of pairs // whose difference is atmost K int pair = 0 ; int index = 0 ; // Loop to consider the consecutive // pairs of the array while (index < arr.length - 1 ) { // if Pair found increment // the index by 2 if (arr[index + 1 ] - arr[index] <= k){ pair += 1 ; index += 2 ; } else { index += 1 ; } } return pair ; } // Driver Code public static void main (String[] args) { int arr[] = { 1 , 4 , 3 , 7 , 5 } ; int k = 2 ; // Function Call int count = countPairs(arr, k) ; System.out.println(count); } } // This code is contributed by AnkitRai01 |
Python3
# Python3 implementation to count the # number of pairs whose difference # is atmost K in an array # Function to count the # number of pairs whose difference # is atmost K in an array def countPairs(arr, k): # Sorting the Array arr.sort() # Variable to store the count of pairs # whose difference is atmost K pair = 0 index = 0 # Loop to consider the consecutive # pairs of the array while (index < len (arr) - 1 ): # if Pair found increment # the index by 2 if arr[index + 1 ] - arr[index] < = k: pair + = 1 index + = 2 else : index + = 1 return pair # Driver Code if __name__ = = "__main__" : arr = [ 1 , 4 , 3 , 7 , 5 ] k = 2 # Function Call count = countPairs(arr, k) print (count) |
C#
// C# implementation to count the // number of pairs whose difference // is atmost K in an array using System; class GFG { // Function to count the // number of pairs whose difference // is atmost K in an array static int countPairs( int []arr, int k) { // Sorting the Array Array.Sort(arr) ; // Variable to store the count of pairs // whose difference is atmost K int pair = 0; int index = 0; // Loop to consider the consecutive // pairs of the array while (index < arr.Length - 1) { // if Pair found increment // the index by 2 if (arr[index + 1] - arr[index] <= k) { pair += 1 ; index += 2 ; } else { index += 1; } } return pair ; } // Driver Code public static void Main () { int []arr = {1, 4, 3, 7, 5} ; int k = 2; // Function Call int count = countPairs(arr, k) ; Console.WriteLine(count); } } // This code is contributed by AnkitRai01 |
Javascript
<script> // Javascript implementation to count the // number of pairs whose difference // is atmost K in an array // Function to count the // number of pairs whose difference // is atmost K in an array function countPairs(arr, k, n) { // Variable to store the count of pairs // whose difference is atmost K let pair = 0; let index = 0; //int n = sizeof(arr)/sizeof(arr[0]); // Sorting the Array arr.sort((a, b) => a - b) ; // Loop to consider the consecutive // pairs of the array while (index < n -1) { // if Pair found increment // the index by 2 if (arr[index + 1] - arr[index] <= k){ pair += 1 ; index += 2 ; } else { index += 1; } } return pair ; } // Driver Code let arr = [1, 4, 3, 7, 5]; let k = 2; let n = arr.length; // Function Call let count = countPairs(arr, k,n); document.write(count + "<br>" ); // This code is contributed by _saurabh_jaiswal </script> |
2
Performance Analysis:
- Time Complexity: In the above-given approach, there is sorting of the array which takes O(N logN), and also there is also one iteration to count the number of pairs which is O(N).
Hence, the overall complexity of the approach is O(N logN + N). - Space Complexity: In the above-given approach, there is no extra space. Hence, the overall space complexity of the approach will be O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!