This problem was asked by Stripe.

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

I wrote the solutions in Swift. Feel free to comment with your solution in the language of your choice.

var myArray = [3, 4, -1, 1]

func firstMissingPositiveInt(_ :[Int]) -> Int {

  var smallest = myArray[0], largest = myArray[0]
  var missing = Int()
  var included = false


  // Find smallest and largest Int
  for integer in myArray {
    if integer < smallest {
      smallest = integer
    }

    if integer > largest {
      largest = integer
    }
  }

  // If missing Int smaller than smallest
  if smallest > 1 {
    missing = smallest - 1
  // If both the smallest and largest Int are less than 0
  } else if smallest < 1 && largest < 1 {
    missing = 1
  // If missing Int greater than smallest
  } else {
    smallest = smallest < 1 ? 1 : smallest

    for value in smallest...largest+1 {
      for integer in myArray {
        if value == integer { included = true }
      }
      if !included { missing = value; break }
      if included { included = false }
    }
  }
  return missing
}

firstMissingPositiveInt(myArray)

print("The first missing Int is \(firstMissingPositiveInt(myArray)).")

This problem was provided by Daily Coding Problem. Get exceptionally good at coding interviews by solving one problem every day.

Leave a Reply