Leena Lavanya

September 4, 2018

Daily Coding Problem: Problem #3

The Daily Coding Problem (Day 3) was given an array of integers, to return the first postive integer missing. The inputed array could contain duplicate and negative numbers. For instance, given an array of [-2 -1, 4, 4, 1, 3], the program should return 2. The solution below was to first create a vector of all the non-negative and non-zero integers inputed and then loop from 1 to the largest integer in the vector, looking for the first one missing.

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

int main()
{
    vector<int> ints;
    int n;
    
    while (cin >> n)  if (n > 0)  ints.push_back(n);
    
    for (int i = 1; i <= (*max_element(ints.begin(), ints.end()) + 1); i++) if (find(ints.begin(), ints.end(), i) == ints.end()) {cout << i << endl; break;}
}
© Copyright 2021 Leena Lavanya. Icons by Font Awesome. Image Credit: Taras Shypka on Unsplash.