Find Lowest Positive Integer

Given an array of integers, this problem asks you to find the lowest positive integer that is not present in the array. You are to do this in linear time and constant space.

Problem

Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The solution is to sort the array and then iterate through it to find the first missing positive integer.
// This solution is optimal because it is linear time and constant space.

function findFirstMissingPositiveInteger(arr) {
  arr.sort((a, b) => a - b);
  let i = 0;
  while (arr[i] <= 0) {
    i++;
  }
  let j = i;
  while (arr[j] === j - i + 1) {
    j++;
  }
  return j - i + 1;
}

console.log(findFirstMissingPositiveInteger([3, 4, -1, 1]));
console.log(findFirstMissingPositiveInteger([1, 2, 0]));

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The approach is to sort the array and then iterate through it to find the first missing positive integer. This solution is optimal because it is linear time and constant space.

Evaluated at: 2022-11-23 00:16:45