[InterviewBit] First Missing Integer

First Missing Integer

  • binary search solution
  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
int Solution::firstMissingPositive(vector<int> &A) {
sort(begin(A), end(A));
auto it = upper_bound(begin(A), end(A),0);
int res = 1;
while(it != end(A) and *it == res) {
res++;
it++;
}
return res;
}

  • two pointer way solution
  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
int Solution::firstMissingPositive(vector<int> &A) {
int res = 1;
unordered_set<int> us;
for(auto& a : A) {
if(a <= 0) continue;
us.insert(a);
while(us.count(res)) {
us.erase(res);
res++;
}
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/20/PS/interviewbit/first-missing-integer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.