Count all Distinct Pairs with difference Equal to K in Java

Given an integer array a[] and a positive integer k, our task is to count all different pairs with differences equal to k.

Example 1:

Input:

int a[] = {1, 6, 7, 9, 3, 2, 8, 10}

int k = 1

Output:

The total number of pairs with a difference equal to k is 6

Explanation:

For the given a[], let's calculate the difference between the elements such that it should be equal to k = 1. {(7 - 6 = 1); (9 - 8 = 1); (10 - 9 = 1); (3 - 2 = 1); (2 - 1 = 1); (8 - 7 = 1)}. Therefore, the pairs are {7, 6}, {9, 8}, {10, 9}, {3, 2}, {2, 1}, {8, 7}. Hence, the total number of pairs is 6.

Example 2:

Input:

int a[] = {2, 8, 5, 3, 10, 4, 12}

int k = 2

Output:

The total number of pairs with a difference equal to k is 4

Explanation:

For the given a[], let's calculate the difference between the elements such that it should be equal to k = 1. {(5 - 3 = 2); (10 - 8 = 2); (4 - 2 = 2); (12 - 10 = 2)}. Therefore, the pairs are {5, 3}, {10, 8}, {4, 2}, {12, 10}. Hence, the total number of pairs is 4.

Approach: Naïve approach

A simple strategy would be to look over each pair individually and determine how one differs from the others. The code that follows implements this simple reply. Two loops are executed, one of which selects the first element in the pair and the other of which searches for the other element. As the goal is to count only different pairings, this technique is ineffective if the array contains duplicates.

Algorithm:

Step 1: Initialize the array a[] and k that represents the difference.

Step 2: Iterate over each element present in the array a[].

Step 3: Iterate through the remaining items of the array (beginning at a[i+1]) for each element a[i].

Step 4: Determine whether the difference between each pair of elements (a[i], a[j]) is equal to K or -K.

Step 4.1: In that case, increment the value of the cnt variable, which counts the number of pairings that have the specified difference K.

Step 5: Lastly, give back the number of these distinct pairings.

Implementation:

FileName: NaiveCOuntingDiffPairs.java

Output:

The total number of pairs with difference equal to k is: 4

Complexity Analysis:

The Time Complexity of the above code is O(N2), where 'N' represents the length of the given array and the Space complexity is O(1).

Approach: Using Binary Search-Sorting

The approach provided uses the sorting method of Arrays. sort(), which arranges the input array's elements in ascending order. This sorting method rearranges the array elements in place; it is probably based on quicksort or merge sort. Sorting the array is a necessary first step since it groups together components that are similar, makes duplicate removal easier, and makes it easier to find pairs with the desired difference in an efficient binary search. By facilitating quicker actions on the sorted array, the sorting process improves the algorithm's overall efficiency.

Algorithm:

Step 1: Set the count to 0 initially.

Step 2: Sort each element in ascending order.

Step 3: Evaluate the array for duplicates.

Step 4: Perform each element a[i] as follows.

Step 4.1: From i+1 to n-1, perform a binary search in the subarray for arr[i] + k.

Step 4.2: Increase the count if arr[i] + k is found.

Step 5: Calculate the count and return the count.

Implementation:

FileName: SortingCountDiffPairs.java

Output:

The total number of pairs with difference equal to k is: 4

Complexity Analysis:

The Time Complexity of the above code is O(N*logN), where 'N' represents the length of the given array and the Space complexity is O(logN).

Approach: Using Self-balancing BST

The above approach efficiently controls the input elements by using an AVL tree. The AVL tree rotates as needed during insertion to preserve its balanced structure and guarantee that the difference in height between the left and right subtrees is not greater than one. Search operations are optimized by this well-balanced structure.

The AVL tree is recursively scanned in the countPairsWithDiffK function to find pairs that have a given difference of k. By avoiding counting duplicates during traversal, the usage of a HashSet improves efficiency. The AVL tree is a good choice for finding pairings in the input data that differ by a specific amount because of its self-balancing feature and effective search capabilities.

Algorithm:

Step 1: Declare a class called Node in order to represent nodes in the AVL tree. The height of left and right child node references, and key value are all contained in each node.

Step 2: Put the insert function into operation to balance the AVL tree while adding a key.

Step 2.1: Modify the ancestor nodes' heights and rotate the tree as needed to keep it balanced.

Step 3: Use the Rotateleft and Rotateright functions to rotate subtrees to the left and right, respectively, in order to keep the subtrees balanced throughout insertion.

Step 4: Declare a function called getBalanceFactor that will compute a node's balance factor, which is the height difference between its left and right subtrees.

Step 5: Put the countPairsWithDiffK function into operation to count pairs that have a certain difference K.

Step 5.1: Find pairings that match the requirement by recursively traversing the AVL tree and storing encountered key values in a HashSet.

Step 6: Call the countPairsWithDiffK function with the given difference k after creating an instance of CountPairsWithDiffK and inserting entries into the AVL tree.

Step 7: Display the total number of pairs with the given difference (k).

Implementation:

FileName: CountPairsWithDiffK.java

Output:

The total number of pairs with difference equal to k is: 4

Complexity Analysis:

The Time Complexity of the above code is O(N*logN), where 'N' represents the length of the given array and the Space complexity is O(N).

Approach: Using Hashing

A very basic scenario in which hashing operates in O(n) time complexity in which the range of values is relatively limited. For instance, the range of values is taken to be 0 to 99999 in the implementation that follows. It is possible to utilize a straightforward hashing method that uses values as an index.

Algorithm:

Step 1: Initialize the count to 0 primarily.

Step 2: Fill a hash map with each unique element of a[]. If an element is already in the hash map, ignore it while inserting.

Step 3: Carry out each element a[i] as follows.

Step 3.1: Search the hash map for a[i] + K; if it is found, increase the count.

Step 3.2: Search the hash map for a[i] - K; if it is found, increase the count.

Step 3.3: Eliminate arr[i] from the hash table.

Step 4: Return the count

Implementation:

FileName: HashingCountDistinctPairs.java

Output:

The total number of pairs with difference equal to k is: 4

Complexity Analysis:

The Time Complexity of the above code is O(N), where 'N' represents the length of the given array and the Space complexity is O(N).