Skip to content

Instantly share code, notes, and snippets.

@baras
Last active September 23, 2020 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baras/533fad030eac3a3fec935aea38029e18 to your computer and use it in GitHub Desktop.
Save baras/533fad030eac3a3fec935aea38029e18 to your computer and use it in GitHub Desktop.
Given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
/**
* Finds the smallest positive integer which does not exist in an array.
*
* @param array $a
* The array to check.
*
* @return int
* The smallest positive integer not found in $a.
*/
function solution2(array $a) {
// We only want the smallest positive number so we start at 1.
$i = 1;
// Iterate through positive integers until we reach the 1st number not in $a.
while (in_array($i, $a)) {
$i++;
}
return $i;
}
// This example will output: 5.
echo solution([1, 3, 6, 4, 1, 2]);
// This example will output: 4.
echo solution([1, 2, 3]);
// This example will output: 1.
echo solution([-1, -3]);
@wadleo
Copy link

wadleo commented Oct 8, 2018

Your solution is true but has poor time complexity: O(N**2) which is not good. Thanks anyways

@cemceliks
Copy link

This one is O(N) or O(N * log(N))
function solution($A) {
sort($A);
$result = 0;
foreach($A as $ix) if ($ix > $result) if($ix == ($result + 1)) $result += 1;
return ($result +1);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment