Given an unsorted integer array, print all pairs with a given difference k in it.

For example,

Input:
 
arr = [1, 5, 2, 2, 2, 5, 5, 4]
k = 3
 
Output:
 
(2, 5) and (1, 4)

Practice this problem

A naive solution would be to consider every pair in a given array and return if the desired difference is found. The time complexity of this solution would be O(n2), where n is the size of the input.

 
We can use a set to solve this problem in linear time. The idea is to insert each array element arr[i] into a set. We also check if element (arr[i] - diff) or (arr[i] + diff) already exists in the set or not. If the element is seen before, print the pair (arr[i], arr[i] - diff) or (arr[i] + diff, arr[i]).

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

(5, 2)
(5, 2)
(5, 2)
(5, 2)
(5, 2)
(4, 1)

Java


Download  Run Code

Output:

(5, 2)
(5, 2)
(5, 2)
(5, 2)
(5, 2)
(4, 1)

Python


Download  Run Code

Output:

(5, 2)
(5, 2)
(5, 2)
(5, 2)
(5, 2)
(4, 1)

The time complexity of the above solution is O(n) and requires O(n) extra space. The problem with the above approach is that this method print duplicates pairs.

How to handle duplicates?

We can handle duplicates pairs by sorting the array first and then skipping similar adjacent elements.

C++


Download  Run Code

Output:

(1, 4)
(2, 5)

Java


Download  Run Code

Output:

(1, 4)
(2, 5)

Python


Download  Run Code

Output:

(1, 4)
(2, 5)

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the size of the input.

 
Also See:

Find pairs with difference k in an array ( Constant Space Solution)