- 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

# Count all distinct pairs with difference equal to k in C++

In this tutorial, we will be discussing a program to find the distinct pairs with difference equal to k.

For this we will be provided with an integer array and the value k. Our task is to count all the distinct pairs that have the difference as k.

## Example

#include<iostream> using namespace std; int count_diffK(int arr[], int n, int k) { int count = 0; //picking elements one by one for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) count++; } return count; } int main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is" << count_diffK(arr, n, k); return 0; }

## Output

Count of pairs with given diff is 2

- Related Questions & Answers
- Find all distinct pairs with difference equal to k in Python
- Count pairs from two arrays having sum equal to K in C++
- Count all pairs with given XOR in C++
- Count all pairs of an array which differ in K bits in C++
- Count number of substrings with exactly k distinct characters in C++
- Count pairs of natural numbers with GCD equal to given number in C++
- Count of index pairs with equal elements in an array in C++
- Print all pairs in an unsorted array with equal sum in C++
- Count pairs formed by distinct element sub-arrays in C++
- Subarray pairs with equal sums in JavaScript
- Find N distinct numbers whose bitwise Or is equal to K in Python
- Find N distinct numbers whose bitwise Or is equal to K in C++
- Count subarrays with all elements greater than K in C++
- Count numbers whose difference with N is equal to XOR with N in C++
- XOR of all elements of array with set bits equal to K in C++

Advertisements