Skip to content

Instantly share code, notes, and snippets.

@dasider41
Created September 15, 2019 20:33
Show Gist options
  • Save dasider41/1157ff5deab50b82963a2e43439d0634 to your computer and use it in GitHub Desktop.
Save dasider41/1157ff5deab50b82963a2e43439d0634 to your computer and use it in GitHub Desktop.
/*
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A of N integers, returns the smallest 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.
Write an efficient algorithm for the following assumptions:
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].
*/
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
const max = A.reduce(function(a, b) {
return Math.max(a, b);
});
if (max <= 0) {
return 1;
}
for (i = 1; i <= max; i++) {
if (!A.includes(i)) {
return i;
}
}
return max + 1;
}
var A = [1, 3, 6, 4, 1, 2];
console.log(solution(A) === 5);
var A = [1, 2, 3];
console.log(solution(A) === 4);
var A = [-1, -3];
console.log(solution(A) === 1);
@charitha200
Copy link

14 answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment