Find K-th Smallest Pair Distance in C++

C++Server Side ProgrammingProgramming

Suppose we have an integer array; we have to find the kth smallest distance among all the pairs. The distance of a pair (A, B) is actually the absolute difference between A and B. So if the input is like [1,3,8], then all possible pairs are [1,3], [3, 8], [1, 8], then when k = 2, the second smallest distance is 5 (8 - 3).

To solve this, we will follow these steps −

  • n := size of nums, x := 0
  • for initialize i := 0, when i < n, update (increase i by 1), do −
    • x := maximum of x and nums[i]
  • Define an array cnt of size x + 1
  • for initialize i := 0, when i < n, update (increase i by 1), do −
    • for initialize j := i + 1, when j < n, update (increase j by 1), do −
      • increase cnt[|nums[j] - nums[i]|] by 1
  • for initialize i := 0, when i <= x, update (increase i by 1), do −
    • if cnt[i] >= k, then −
      • return i
    • k := k - cnt[i]
  • return x

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int smallestDistancePair(vector<int>& nums, int k) {
      int n = nums.size();
      int x = 0;
      for(int i = 0; i < n; i++)x = max(x, nums[i]);
      vector <int> cnt(x + 1);
      for(int i = 0 ; i < n; i++){
         for(int j = i + 1; j < n; j++){
            cnt[abs(nums[j] - nums[i])]++;
         }
      }
      for(int i = 0; i <= x; i++){
         if(cnt[i] >= k)return i;
         k -= cnt[i];
      }
      return x;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,3,8};
   cout << (ob.smallestDistancePair(v, 2));
}

Input

{1,3,8}

Output

5
raja
Published on 02-Jun-2020 10:41:25
Advertisements