- 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

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.

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.

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)

Running the above code gives us the following result −

Required Pairs: 3

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.

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)

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++
- Python - Total equal pairs in List
- Python program to find sum of absolute difference between all pairs in a list
- Find Maximum difference between tuple pairs in Python
- Print all pairs in an unsorted array with equal sum in C++
- 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
- Find the number of distinct pairs of vertices which have a distance of exactly k in a tree in Python
- Program to find number of distinct combinations that sum up to k in python

Advertisements