![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
K-diff Pairs in an Array in C++
Suppose we have an array and an integer k, we have to find the number of unique k-diff pairs in the array. Here the k-diff pair is like (i, j), where i and j are both are present in the array and their absolute difference is k.
So, if the input is like [3,1,4,1,5], k = 2, then the output will be 2, as there are two 2-diff pairs in the array-like (1,3) and (3,5).
To solve this, we will follow these steps −
Define maps called seen and done
Define one set s
if k < 0, then −
return 0
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
(increase seen[nums[i]] by 1)
insert nums[i] into s
ans := 0
for each element it in s, do −
if k is same as 0, then −
if seen[it] > 1, then −
(increase ans by 1)
Otherwise
increase done[it] by 1
if (it + k) is in seen but not in done, then −
(increase ans by 1)
if (it - k) is in seen but not in done, then −
(increase ans by 1)
return ans
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h&g; using namespace std; class Solution { public: int findPairs(vector<int>& nums, int k) { map<int, int> seen, done; set<int> s; if (k < 0) return 0; for (int i = 0; i < nums.size(); i++) { seen[nums[i]]++; s.insert(nums[i]); } int ans = 0; for (auto it = s.begin(); it != s.end(); it++) { if (k == 0) { if (seen[*it] > 1) ans++; } else { done[*it]++; if (seen.find(*it + k) != seen.end() && done.find(*it + k) == done.end()) ans++; if (seen.find(*it - k) != seen.end() && done.find(*it - k) == done.end()) ans++; } } return ans; } }; main(){ Solution ob; vector<int> v = {3,1,4,1,5}; cout << (ob.findPairs(v, 2)); }
Input
{3,1,4,1,5}, 2
Output
2