Free test

that, given an array A of N integers, returns the biggest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1.

by Rene Rubio

HTML

<p>

</p>

JavaScript

function solution(A) {
    // Implement your solution here
    const sortList = A.sort((a,b)=>b - a)
    const biggest = sortList.reduce((prev,curr)=>{
        if(prev <= curr) prev = curr
        return prev
    },0)
    let notOccurIn = biggest === 0 ? 1 : biggest 
    for (let num of sortList){
      if(num === notOccurIn){
            notOccurIn--
        } else if ( num > notOccurIn ){
            break
        }
    }
    //console.log(notOccurIn === 0 ? biggest + 1 : notOccurIn)
    return notOccurIn === 0 ? biggest + 1 : notOccurIn
}
console.log( solution( [1, 3, 6, 4, 1, 2]) )