How to get the first missing smallest positive integer in an unsorted integer array with PHP

1 Answer

0 votes
function findSmallestMissingNumber($arr) {
    $numSet = array_flip($arr); // Convert array to an associative array for fast lookup

    $index = 1;
    while (true) {
        if (!isset($numSet[$index])) {
            return $index;
        }
        $index++;
    }
}


$arr = [3, 4, -1, 1];

echo findSmallestMissingNumber($arr);



/*
run:

2

*/

 



answered Jun 4 by avibootz
...