HackerRank 'Closest Numbers' Solution

by Srikant Padala on May 31, 2016, 3:46 pm


Explanation


  • Sort the array.
  • Find the absolute difference between consecutive pairs only.
  • Find the minimum of all the absolute differences.
  • Print all the pairs corresponding to the minimum absolute difference.

Closest Numbers Problem Statement

Video

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;

void closestMinPair(vector<int> &arr) {
    vector<int> diff(arr.size());
    sort(arr.begin(), arr.end());
    int min = INT_MAX;
    for(int i=1; i < arr.size(); i++) {
        diff[i] = arr[i]- arr[i-1];
        if(min > diff[i]) min = diff[i];
    }
    for(int i=1; i < arr.size(); i++) {
        if(diff[i] == min) cout << arr[i-1] << " " << arr[i] << " ";
    }
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int i=0; i < n; i++) {
        cin >> arr[i];
    }
    closestMinPair(arr);
    return 0;
}

Coming Soon.