meta data for this page
  •  

First Missing Positive

Leetcode


Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

Example 1:

Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.

Solution 1

Solution 1

public int firstMissingPositive(int[] nums) {
  if (nums.length == 1) {
    return nums[0] == 1 ? 2 : 1;
  }
 
  boolean[] posNums = new boolean[nums.length];
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] > 0 && nums[i] <= nums.length) posNums[nums[i] - 1] = true;
  }
 
  for (int i = 0; i < posNums.length; i++) {
    if (!posNums[i]) return i + 1;
  }
 
  return posNums.length + 1;
}