Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find all distinct pairs with difference equal to k in Python
In this article, we will learn how to find all distinct pairs of numbers in a list where the absolute difference between the two numbers equals a given value k. We'll explore different approaches to solve this problem efficiently.
Using Nested for Loops
This approach uses two nested for loops to compare every possible pair of elements in the list. The outer loop visits each element, while the inner loop compares it with all remaining elements ?
numbers = [5, 3, 7, 2, 9]
k = 2
count = 0
# Check all possible pairs
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if abs(numbers[i] - numbers[j]) == k:
count += 1
print(f"Pair found: ({numbers[i]}, {numbers[j]})")
print("Total pairs:", count)
Pair found: (5, 3) Pair found: (5, 7) Pair found: (9, 7) Total pairs: 3
Using Sorted Array with Two Pointers
This optimized approach sorts the array first, then uses two pointers to efficiently find pairs. This reduces the time complexity from O(n²) to O(n log n) ?
numbers = [5, 3, 7, 2, 9]
k = 2
count = 0
# Sort the array for two-pointer approach
numbers.sort()
print("Sorted array:", numbers)
left = 0
right = 1
while right < len(numbers):
diff = numbers[right] - numbers[left]
if diff == k:
count += 1
print(f"Pair found: ({numbers[left]}, {numbers[right]})")
left += 1
right += 1
elif diff < k:
right += 1
else:
left += 1
if left == right:
right += 1
print("Total pairs:", count)
Sorted array: [2, 3, 5, 7, 9] Pair found: (3, 5) Pair found: (5, 7) Pair found: (7, 9) Total pairs: 3
Using Set for O(n) Solution
The most efficient approach uses a set to check if the required pair element exists. This achieves O(n) time complexity ?
numbers = [5, 3, 7, 2, 9]
k = 2
pairs = []
number_set = set(numbers)
for num in numbers:
target = num + k
if target in number_set and (num, target) not in pairs:
pairs.append((num, target))
print(f"Pair found: ({num}, {target})")
print("Total pairs:", len(pairs))
Pair found: (5, 7) Pair found: (3, 5) Pair found: (7, 9) Total pairs: 3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops | O(n²) | O(1) | Small datasets |
| Two Pointers | O(n log n) | O(1) | Medium datasets |
| Set Lookup | O(n) | O(n) | Large datasets |
Conclusion
Use the set-based approach for optimal O(n) performance with large datasets. The two-pointer method offers a good balance of efficiency and space usage. The nested loop approach is simple but only suitable for small datasets.
