
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- Count pairs formed by distinct element sub-arrays in C++
- Print all pairs in an unsorted array with equal sum in C++
- Count subarrays with all elements greater than K in C++
- 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 numbers whose difference with N is equal to XOR with N in C++
- Program to find out the k-th smallest difference between all element pairs in an array in C++
- XOR of all elements of array with set bits equal to K in C++

Advertisements