Program to find out the k-th smallest difference between all element pairs in an array in C++

Suppose we are given a list containing several integer numbers. We have to find out the difference between each pair of values in the array and find out the k-th smallest difference number. The index starts at 0 and the value k is given to us as input.

So, if the input is like numbers = {2, 6, 4, 8}, k = 2, then the output will be 2.

The differences between the pairs are −

(2, 6) = 4

(2, 4) = 2

(2, 8) = 6

(6, 4) = 2

(6, 8) = 2

(4, 8) = 4

If we sort the values, it becomes 2, 2, 2, 4, 4, 6. The 2-nd smallest value is 2. (Index starts from 0).

To solve this, we will follow these steps −

  • increase k by 1
  • sort the array input
  • le := 0
  • ri := last element of input - first item of input
  • while le
  • mid := (le + ri) / 2
  • tmp := 0
  • lp := 0
  • for initialize i := 1, when i
  • while input[i] - input[lp] > mid, do −
    • lp := lp + 1
  • tmp := tmp + i - lp
  • if tmp >= k, then −
    • ri := mid
  • Otherwise
    • le := mid + 1
  • return le
  • Example

    Let us see the following implementation to get better understanding −

    #include
    
    using namespace std;
    
    int solve(vector& input, int k) {
    k++;
    sort(input.begin(), input.end());
    int le = 0;
    int ri = input.back() - input[0];
    while (le  mid) lp++;
    tmp += i - lp;
    }
    if (tmp >= k)
    ri = mid;
    else
    le = mid + 1;
    }
    return le;
    }
    int main() {
    vector numbers = {2, 6, 4, 8};
    cout

    Input

    vector numbers = {2, 6, 4, 8};
    cout

    Output

    2
    Updated on: 2021-10-19T12:19:45+05:30

    430 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements