In JavaScript you can do this:
First, order your array using the JavaScript
Array.sort()
method, with complexity \$O(n\log(n))\$ (explained here):var A=[4,3,2,1,0,-3]; A.sort(function(a, b){return a-b}); //returns the array ordered [-3,0,1,2,3,4]
Only iterate over the ordered array. For every value, check if the value is bigger than 0 and if the next element on the array is not equal to the current value + 1.
First, remove duplicates if anyfunction(A){ for(var i=0;i<A.length-1;i++){// iterate until penultimate element if(A[i]>0 && A[i+1]!=(A[i]+1)){ return (A[i]+1); } } }
var A=[4,3,2,1,0,1,-3];
const remove_duplicates = A.filter((number, index) => {
return A.indexOf(number) === index
})
Secondly, order your array using the JavaScript
Array.sort()
method, with complexity \$O(n\log(n))\$ (explained here):const sorted = remove_duplicates.sort(function(a, b){return a-b}); //returns the array ordered [-3,0,1,2,3,4]
Only iterate over the ordered array. For every value, check if the value is bigger than 0 and if the next element on the array is not equal to the current value + 1.
// find smallest positive integer not in sorted greater than 0
// return only valid number, unless all negative values else return 1
const result = sorted.map((number, index) => {
if (number > 0 && sorted[index + 1] !== sorted[index] + 1) {
return sorted[index] + 1
}
}).filter(number => number !== undefined)[0]
return result === undefined ? 1 : result