Support Ticket Why UserCV? [FAQ] Knowledgebase Personal Blogging Platform Start Teaching Online
Company is going under Migratiiion - Some of the functionalities may not be available for the time being.
Return the Smallest positive integer greater than 0 that does not exist in Array

People, out there must be giving some interview and find a hard time understanding technical question that comes to them. I will start with the most basic tests. Let's consider the below task:

Write a function:

function solution($array);

that, given an array a $array of N integers, which returns the smallest positive integer that does not occur in a $array variable. return must be greater than 0.

For example, given $array = [1, 2, 6, 4, 4, 3], the function should return 5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.


  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [−1,000,000..1,000,000]

Check out the below Code for solution:


function solution($array) {
    $low = 1;
    // Get the lowest value in array
    $min = min($array);
    // Get the largest value in array
    $max = max($array);
    // run the loop from minimal to maximum value
    for($i = 1;$i<=$max;$i++) {
        // Check if current index is the last value or max value of assumption.
        if(count($array) != $i || $i > 100000) {
            // Check if the current index exists in array or not, if it doesn't then return
            if(!in_array($i, $array)) {
                return $i;
        } else {
            // if count is equal or max, return value with +1
            return $i > 1 && !in_array(1, $array) ? 1 : $i + 1;
    return $low;


I hope, the comment will help you easier to understand the above code.

Any question asks them below.

Tags: code test interview technical test interview programming test programmer interview technical round algorithm test technical job interview test

About the Author