##### 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.

Assuming:

• 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.

•  ##### Full Stack Programmer and Engineer

I am Full Stack Programmer and Engineer. I develop web apps, mobile apps at the best price. My skills are listed at below section. I also write sometimes blog about various tech stacks. Feel free to follow me on my social media channels listed below.

From: Jaipur, Rajasthan India - Last Login: 2 days ago.

0 out of 5