Open In App

Python | Find all distinct pairs with difference equal to k

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of integers and a positive integer k, write a Python program to count all distinct pairs with difference equal to k. 

Examples:

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

Input : [8, 12, 16, 4, 0, 20], k = 4
Output : [(8, 4), (12, 8), (16, 12), (4, 0), (20, 16)]

  Approach #1 : Python list comprehension We will use list comprehension using two loops using ‘e1’ and ‘e2’ that will traverse given list. We check if e1-e2 == k or not and return the (e1, e2) tuple respectively. Finally, a list with required tuples will be returned. 

Python3




# Python3 program to Find all distinct
# pairs with difference equal to k
 
def findPairs(lst, k):
     
    return [(e1, e2) for e1 in lst
            for e2 in lst if (e1-e2 == k)]
         
# Driver code
lst = [1, 5, 3, 4, 2]
k = 3
print(findPairs(lst, k))


Output:

[(5, 2), (4, 1)]

  Approach #2 : This is an efficient approach with respect to the above approach as it uses only O(n) space. We take an empty list to store the output. Then, we use a loop with iterator ‘e’ to traverse through given list. In every iteration, we check is e+k i.e the required pair integer for e is available or not. If yes, we append the tuple to ‘res’. 

Python3




# Python3 program to Find all distinct
# pairs with difference equal to k
 
def findPairs(lst, k):
    res = []
    for e in lst:
        if e + k in lst:
            res.append(tuple((e, e + k)))
             
    return res
     
# Driver code
lst = [1, 5, 3, 4, 2]
k = 3
print(findPairs(lst, k))


Output:

[(1, 4), (2, 5)]

  Approach #3 : combinations() from itertools module The best approach is to use the inbuilt function from itertools module. combinations() produces an iterator over tuples of all combinations of n elements in inputs. We make the use of these combinations and output those having ‘k’ difference. 

Python3




# Python3 program to Find all distinct
# pairs with difference equal to k
from itertools import combinations
 
def findPairs(lst, k):
    return [(x, y) for x, y in combinations(lst, r = 2)
                   if abs(x - y) == k]
             
# Driver code
lst = [1, 5, 3, 4, 2]
k = 3
print(findPairs(lst, k))


Output:

[(1, 4), (5, 2)]

 Approach #4 : Hash set approach: Use a hash set to store the elements of the list.  This approach has a time complexity of O(n) and a space complexity of O(n).

To implement this approach, we can do the following:

  1. Create an empty hash set.
  2. Iterate through the list of integers and add each element to the hash set.
  3. For each element in the list, check if (element + k) , (element-k) is in the hash set. If it is, add the pair (element, element + k) to the result list.

Here is some sample code that illustrates this approach:

Python3




def findPairs(lst, k):
    # Initialize an empty list to store the pairs
    result = []
    # Initialize an empty hash set to store the elements of the list
    elements = set()
    # Iterate through the list
    for element in lst:
        # Add the element to the hash set
        elements.add(element)
        # Check if (element + k) is in the hash set
        if (element + k) in elements:
            # If it is, add the pair (element, element + k) to the result list
            result.append((element, element + k))
        elif (element - k) in elements:
            # If it is, add the pair (element, element + k) to the result list
            result.append((element - k, element))
    # Return the result list
    return result
# Example input
lst = [1, 5, 3, 4, 2]
k = 3
 
# Call the function
result = findPairs(lst, k)
 
# Print the result
print(result)
#This code is contributed by Edula Vinay Kumar Reddy


Output

[(1, 4), (2, 5)]

Approach#5: Using set and array slicing

 In this approach, we first sort the input array. Then, we use set and array slicing to efficiently find all distinct pairs whose difference is equal to k. We iterate over the sorted array and check if the element arr[i]+k exists in the subarray arr[i+1:]. If it does, we add the pair (arr[i], arr[i]+k) to our set of distinct pairs. 

Algorithm

  •  Initialize an empty set to store the distinct pairs
  •  Sort the input list
  •  For each element in the sorted list, check if there exists another element in the list whose difference i
  •  If such an element is found, add the pair (element, element-k) to the set of distinct pairs
  •  Return the set of distinct pairs

Python3




def distinct_pairs(arr, k):
    arr.sort()
    distinct_pairs = set()
    for i in range(len(arr)):
        if arr[i]+k in arr[i+1:]:
            distinct_pairs.add((arr[i], arr[i]+k))
    return distinct_pairs
arr = [1, 5, 3, 4, 2]
k = 3
print(distinct_pairs(arr, k))


Output

{(2, 5), (1, 4)}

Time complexity: O(nlogn), where n is the length of array
Space complexity: O(n), where n is the length of array

Using numpy:

Algorithm:

  • Convert the list into a numpy array.
  • Sort the array in ascending order.
  • Compute the absolute difference between each pair of elements using np.subtract.outer function.
  • Check if the absolute difference is equal to k.
  • If it is equal to k, then the pair is added to the list of pairs.
  • The pairs list is then truncated to remove duplicate pairs and returned.

Python3




import numpy as np
 
def findPairs(lst, k):
    arr = np.array(lst)
    arr_sorted = np.sort(arr)
    idx_pairs = np.where(np.abs(np.subtract.outer(arr_sorted, arr_sorted)) == k)
    pairs = [sorted([arr_sorted[i], arr_sorted[j]])[::-1] for i, j in zip(*idx_pairs)]
 
    return pairs[::2]
 
# Example input
lst = [8, 12, 16, 4, 0, 20]
k = 4
 
# Call the function
result = findPairs(lst, k)
 
# Print the result
print(list(map(tuple, result)))


Output:

[(4, 0), (8, 4), (12, 8), (16, 12), (20, 16)]

Time complexity:
The time complexity of this algorithm is O(n^2), where n is the length of the input list. This is because the np.subtract.outer function takes O(n^2) time to compute the absolute difference between each pair of elements.

Space complexity:
The space complexity of this algorithm is O(n), where n is the length of the input list. This is because we are converting the input list into a numpy array, which takes O(n) space. Additionally, the pairs list can also take up to O(n) space in the worst case.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads