Write a function:
function solution(A);
that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer (greater than 0) that does not occur in A. For example, given:
A[0] = 1 A[1] = 3 A[2] = 6 A[3] = 4 A[4] = 1 A[5] = 2
the function should return 5. Assume that:
• N is an integer within the range [1..100,000]; • each element of array A is an integer within the range
[−2,147,483,648..2,147,483,647].
Complexity: • expected worst-case time complexity is O(N); • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
My Answer is 100% WRONG! What is wrong with it? First let me state the obvious errors
- return value - i return 0, because there is no indication of what to return, if there is no missing integer.
Assumptions I made that may be wrong
- returns the minimal positive integer (greater than 0) that does not occur in A. Here I do not check for negative values
my code, which works on own test cases, and works on negative numbers too, got 0%.
function solution(A) {
// write your code in JavaScript (Node.js 0.12)
A.sort();
var a_length = A.length;
for(var i = 0; i < a_length; i++){
// if i is 0 - 1 = -1 then do not do the following
// if i is 1 - 1 - 0 then do the follow
// if i >= 0 then do the following
if(i - 1 >= 0){
// remember above there is a A.sort() so it
// looks like this
// A[0] = 1
// A[1] = 1
// A[2] = 2
// A[3] = 3
// A[4] = 4
// A[5] = 6
// if A[1] is 1 and A[1-1 = 0] is 1 then this is 1>1 false
// if A[2] is 2 and A[2-1 = 1] is 1 then this is 1>1 false
// if A[3] is 3 and A[3-1 = 2] is 2 then this is 1>1 false
// if A[4] is 4 and A[4-1 = 3] is 3 then this is 1>1 false
// if A[5] is 6 and A[5-1 = 4] is 4 then this is 2>1 true return A[i - 1] + 1 where A[5 - 1 = 4] is 4 + 1 is 5. 5 is returned.
if(A[i] - A[i - 1] > 1){
return A[i - 1] + 1;
}
}
}
// this does not check for negative
// returns the minimal positive integer (greater than 0
// this is a return no minimal positive integer found
return 0;
}
Everything is wrong, example test result:
simple simple test 0.072 s WRONG ANSWER got 3 expected 1
Why does it work for me and not for them.