Daily Coding Problem: Problem #4

Problem

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.

Solution

To solve this, you should think what’s common between array indexes and a
positive integer: it’s the same thing.

So we put each positive integer of an
array at its place (i+1 since we count from 1) and then iterate again to find
first missing.

If we don’t, return length plus one (=next).

Code

funcsolution(aa[]int)int{iflen(aa)==0{return1}for_,a:=rangeaa{// try to place all numbers at same index (from 1)
ifa<0{// we don't care, it's negative
continue}ifa>=len(aa){// we don't care, result always < len(aa)
continue}aa[a-1]=a}fori:=rangeaa{// find first missing
ifaa[i]!=i+1{returni+1}}returnlen(aa)+1// all there
}

UPDATE

As it was mentioned in the comments, the first solution fails in
case of [3,2,4,-1,1]

It happens because when we place an integer to its position in the array,
we also delete integer that used to be in that place.

To avoid this, instead of just placing the integer, I swap it with the current
one and process current index one more time.

funcsolution(aa[]int)int{iflen(aa)==0{return1}fori:=0;i<len(aa);i++{a:=aa[i]ifa<0{// we don't care, it's negative
continue}ifa>=len(aa){// we don't care, result always < len(aa)
continue}ifa==aa[a-1]{// if integer on it's place, skip
continue}// put each integer on it's place
// decrease i, because aa[i] is a new integer now and we need to
// process it one more time
aa[i],aa[a-1]=aa[a-1],aa[i]i--}fori:=rangeaa{// find first missing
ifaa[i]!=i+1{returni+1}}returnlen(aa)+1// all there
}