Find the smallest positive integer that does not occur in a given sequence
100% result solution in Javascript:
function solution(A) {
// only positive values, sorted
A = A.filter(x => x >= 1).sort((a, b) => a - b)
let x = 1
for(let i = 0; i < A.length; i++) {
// if we find a smaller number no need to continue, cause the array is sorted
if(x < A[i]) {
return x
}
x = A[i] + 1
}
return x
}
If the expected running time should be linear, you can't use a TreeSet
, which sorts the input and therefore requires O(NlogN)
. Therefore you should use a HashSet
, which requires O(N)
time to add N
elements.
Besides, you don't need 4 loops. It's sufficient to add all the positive input elements to a HashSet
(first loop) and then find the first positive integer not in that Set (second loop).
int N = A.length;
Set<Integer> set = new HashSet<>();
for (int a : A) {
if (a > 0) {
set.add(a);
}
}
for (int i = 1; i <= N + 1; i++) {
if (!set.contains(i)) {
return i;
}
}
My code in Java, 100% result in Codility
import java.util.*;
class Solution {
public int solution(int[] arr) {
int smallestInt = 1;
if (arr.length == 0) return smallestInt;
Arrays.sort(arr);
if (arr[0] > 1) return smallestInt;
if (arr[arr.length - 1] <= 0) return smallestInt;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == smallestInt) {
smallestInt++;
}
}
return smallestInt;
}
}
JS:
filter
to get positive non zero numbers from A arraysort
above filtered array in ascending ordermap
to iterate loop of above stored resultif
to checkx
is less than the current element then return- otherwise, add 1 in the current element and assign to
x
function solution(A) {
let x = 1
A.filter(x => x >= 1)
.sort((a, b) => a - b)
.map((val, i, arr) => {
if(x < arr[i]) return
x = arr[i] + 1
})
return x
}
console.log(solution([3, 4, -1, 1]));
console.log(solution([1, 2, 0]));