Skip to main content

Leet Code Problem #41 First missing positive

Given an unsorted integer array, find the smallest missing positive integer.
Input:
[1,2,4,5]
Output:
3

Input:
[0,-1,-2,1,5,2];
Output:
3

Input:
[0,-1,-2];
Output:
1
 
Approach to solve the problem:
  1. First iterate over the array and identify all the negative elements including zero.
  2. Where ever you find zero or negative element replace its value with size of array * 2.
  3. Now iterate over the array one more time and mark the value at index.
  4. As current iterator as negative of it, If its iterator value is less than size of the  array.
  5. Ex: if the array if [1, 4, 6, -1, -3], size of the array is 5.
  6. After first iteration it will be [1, 4, 6, 10, 10] (after marking the negative and zero values with double the size of the array).
  7. Next follow step 3, arr[0] = 1 (subract -1 as array index starts from zero)which is less than size of array so, => arr[arr[0]] = - arr[arr[0]].
  8. Next arr[2] = 4 which is less than size of array, so index will be 4 - 1 = 3, so arr[3] = - arr[3]
  9. Next value is 6 ignore next two values is 10 ignore them as well.
  10. Now the array looks like = [-1, 4, 6, -10, 10];
  11. The solution is first non negative value + 1
  12. Now iterate from beginning again, at 0 the value is negative at 1 the value is positive the solution is 1 + 1 which is 2

Solution in C++:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
if(nums.size() == 0)
return 1;
int size = nums.size();
int iter = 0;
int x = 0;
//remvoing negative elements
for(iter = 0; iter < size; ++iter){
if(nums[iter] <= 0){
nums[iter] = nums.size() * 2;
}
}
for(iter = 0; iter < size; ++iter){
x = abs(nums[iter]) - 1;
if(x < size && nums[x] > 0){
nums[x] = -nums[x];
}
}
for(iter = 0; iter < size; ++iter){

if(nums[iter] > 0)
return iter + 1;
}
return size + 1;
}
};

Comments