- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

- Related Questions & Answers
- Count all distinct pairs with difference equal to k in C++
- Find N distinct numbers whose bitwise Or is equal to K in Python
- Python program to find N-sized substrings with K distinct characters
- Find N distinct numbers whose bitwise Or is equal to K in C++
- Program to Find K-Largest Sum Pairs in Python
- Find K Pairs with Smallest Sums in C++
- Program to find out the k-th smallest difference between all element pairs in an array in C++
- Python program to find sum of absolute difference between all pairs in a list
- Python - Total equal pairs in List
- Print all pairs in an unsorted array with equal sum in C++
- Program to find max number of K-sum pairs in Python
- Find Maximum difference between tuple pairs in Python
- Count pairs from two arrays having sum equal to K in C++
- Subarray pairs with equal sums in JavaScript
- Python – N sized substrings with K distinct characters