# Find all distinct pairs with difference equal to k in Python

PythonServer Side ProgrammingProgramming

In this article we are going to see how to count the numbers of pairs of numbers which have an exact difference equal to k. The given numbers are in form of a list and we supply the value of k to the program.

## Using for Loop

In this approach we design two for loops, one inside another. The outer for loop keeps track of visiting each element of the given list. The inner for loop keeps comparing each of the remaining elements with the element of the outer loop and increase the value of the count variable if it matches the required difference.

## Example

listA = [5, 3, 7, 2, 9]

k = 2
count = 0

# Elements of the list
for i in range(0, len(listA)):

# Make pairs
for j in range(i + 1, len(listA)):

if listA[i] - listA[j] == k or listA[j] - listA[i] == k:
count += 1

print("Required Pairs: ",count)

## Output

Running the above code gives us the following result −

Required Pairs: 3

## Using While Loop

In another approach we use the while loop alogn with if else clause. Here we keep incrementing the current and next index depending on whether the difference between the two pairs matches the required difference.

## Example

Live Demo

listA = [5, 3, 7, 2, 9]

k = 2
count = 0

listA.sort()

next_index = 0
current_index = 0

while current_index < len(listA):
if listA[current_index] - listA[next_index] == k:
count += 1
next_index += 1
current_index += 1

elif listA[current_index] - listA[next_index] > k:
next_index += 1
else:
current_index += 1

print("Required Pairs: ",count)

## Output

Running the above code gives us the following result −

Required Pairs: 3