July 10, 2017 Andrey

Missing Numbers Hackerrank problem with C++

https://www.hackerrank.com/challenges/missing-numbers/problem

Solved using sorting two arrays, finding missing number in the loop and putting them in the set.

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

set<int> findMissing(int n, vector <int> ar1, vector <int> ar2) {
    // using default comparison (operator <):
    sort (ar1.begin(), ar1.end()); 
    sort (ar2.begin(), ar2.end()); 
    
    
    set<int> result;
    int temp = 0;
    for (int i = 0; i < ar1.size(); i++){
        if (ar1[i] == ar2[i+temp]) {
            //all good
        } else {
            //missing number found, increase second array pointer, but keep first one the same
            result.insert(ar2[i+temp]);
            temp++;    
            i--;
        }
    } 
    
    //add the rest of the second array  
    for (int i = ar1.size()+temp; i < ar2.size(); i++){
         result.insert(ar2[i]);
    }
     
    
    return result;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    cin >> n;
    vector<int> ar(n);
    for(int ar_i = 0; ar_i < n; ar_i++){
       cin >> ar[ar_i];
    }
    
    cin >> n;
    vector<int> ar2(n);
    for(int ar2_i = 0; ar2_i < n; ar2_i++){
       cin >> ar2[ar2_i];
    }
    set<int> result = findMissing(n, ar, ar2);
    
    // print out content:
   
    for (set<int>::iterator it=result.begin(); it!=result.end(); it++)
         cout << *it << ' ';
    cout << endl;
    return 0;
}