Problem: https://leetcode.com/problems/first-missing-positive/
Solution in C++ #
class Solution {
public:
int firstMissingPositive(vector
int i = 0;
while(i < n) {
if(nums\[i\] > 0 && nums\[i\] <= n && nums\[i\] != nums\[nums\[i\] - 1\]) {
swap(nums\[i\], nums\[nums\[i\] - 1\]);
// we swap ith element with the
// element at position (ith element - 1)
// because we have 0-based indexing
}else{
i++;
}
}
for(int i=0; i<n; i++) {
if(nums\[i\] != i + 1) {
return i + 1;
}
}
return n + 1;
}
};