Skip to content

Instantly share code, notes, and snippets.

@thieunguyencrystal
Created March 21, 2019 11:06
Show Gist options
  • Save thieunguyencrystal/7566544f22052264af42122664c986c4 to your computer and use it in GitHub Desktop.
Save thieunguyencrystal/7566544f22052264af42122664c986c4 to your computer and use it in GitHub Desktop.
Find the smallest positive number missing from an unsorted array
/*
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.
*/
func solution(_ array: [Int]) -> Int {
guard let max = array.max(), max > 0 else { return 1 }
let count = array.count
var temp = Array(repeating: 0, count: max + 1)
for j in (0..<count) {
let value = array[j]
if value > 0 {
temp[value] = -1 // marked
}
}
for i in (1...max) {
if temp[i] == 0 { // found
return i
}
}
return max + 1
}
var input = [3, 4, -1, 1]
let output = solution(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment