First Missing Positive

Monisha Mathew
1 min readApr 18, 2019

--

Question: Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

You may view the full question here.

Approach 1: Let’s dive straight into the code —

//Approach 1:
//Runtime: 0ms
//Memory usage: 37MB
class Solution {
public int firstMissingPositive(int[] nums) {
int flagged = 5;
int[] val = new int[nums.length + 1];
for(int i = 0; i<nums.length; i++){
if(nums[i]>0 && nums[i]<=nums.length){
val[nums[i]] = flagged;
}
}
for(int i = 1; i<nums.length + 1; i++){
if(val[i]!=flagged){
return i;
}
}
return nums.length + 1;
}
}

Find more posts here.

Cheers & Chao!

--

--