HackerRank 'Missing Numbers' Solution

by Srikant Padala on April 25, 2016, 1:40 pm


Explanation


Use Set difference, and unique algorithm

http://www.cplusplus.com/reference/algorithm/set_difference/

http://www.cplusplus.com/reference/algorithm/unique/


Missing Numbers Problem Statement

Video

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

vector<int> &missingNumbers(vector<int> &A, vector<int> &B) {
    sort(A.begin(), A.end());
    sort(B.begin(), B.end());
    vector<int> *resultptr = new vector<int>(1000010);
    //B - A
    auto it = set_difference(B.begin(), B.end(), A.begin(), A.end(), (*resultptr).begin());
    it = unique((*resultptr).begin(), it);
    resultptr->resize(distance((*resultptr).begin(), it));
    return *resultptr;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int n, m,temp;
    vector<int> A, B, result;
    cin >> n;
    for(int i=0; i < n; i++) {
        cin >> temp;
        A.push_back(temp);
    }
    cin >> m;
    for(int i=0; i < m; i++) {
        cin >> temp;
        B.push_back(temp);
    }
    result = missingNumbers(A, B);
    for(int i=0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
    return 0;
}

Coming Soon.