HackerRank 'Pairs' Solution

by Srikant Padala on April 25, 2016, 7:57 am


Explanation


  • Sort the array
  • Compare every element with the elements following it such that a[j] - a[i] <= k.
  • If the difference is k then increment count.

Pairs Problem Statement

Video

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
/* Head ends here */

int pairs(vector < int > a,int k) {
    int ans = 0;
    sort(a.begin(), a.end());
    //1 2 3 4 5
    for(int i=0; i < a.size()-1; i++) {
        for(int j=i+1; j < a.size() && (a[j] - a[i]) <= k; j++) {
            if(a[j] - a[i] == k) ans++;
        }
    }
    return ans;
}

/* Tail starts here */
int main() {
    int res;
    
    int _a_size,_k;
    cin >> _a_size>>_k;
    cin.ignore (std::numeric_limits<std::streamsize>::max(), '
'); 
    vector<int> _a;
    int _a_item;
    for(int _a_i=0; _a_i<_a_size; _a_i++) {
        cin >> _a_item;
        _a.push_back(_a_item);
    }
    
    res = pairs(_a,_k);
    cout << res;
    
    return 0;
}

Coming Soon.