I am attempting this question using javascript. When I run my implementation on the website I get 11%, which asides from poor runtime states that I fail four hidden tests.
I cannot understand how my implementation is failing. I understand its not a great implementation and there are cleaner working answers in the linked question, but I am still curious what false logic I am using.
A = A.filter(a => a > 0).sort()
if (A.length === 0) {
return 1
}
if (A.length === 1) {
return A[0] + 1
}
for (let i = 0; i < A.length; i++) {
let curr = A[i]
let next = A[i + 1]
if (curr !== next && (curr + 1) !== next) {
return curr + 1
}
}
My logic is that since I am traversing a sorted array of positive integers from lowest to highest, if the current element + 1 doesn’t equal the following element (i.e. [5,7] would be 5 + 1 != 7), there is a gap, which is the missing integer.
And if the loop gets all the way to the end, the last if
statement still triggers since next is undefined
, which would return the max value + 1.