Last active
September 23, 2020 01:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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]); |
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
Your solution is true but has poor time complexity: O(N**2) which is not good. Thanks anyways