In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. This question was asked by Stri
This is in Java. Time complexity f O(N) and space complexity O(1)
private static int minimum_positive_integer(int[] arr) {
int i = 0;
int j = arr.length - 1;
//splitting array
while (i < j) {
if (arr[i] > 0) {
i++;
}
if (arr[j] <= 0) {
j--;
}
if (arr[i] <= 0 && arr[j] > 0) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
i++;
j--;
}
}
int len_positive = i;
if (arr[i] > 0) len_positive++;
for (i = 0; i < len_positive; i++) {
int abs = Math.abs(arr[i]);
if (abs <= len_positive) {
int index = abs - 1;
arr[index] = -abs;
}
}
for (i = 0; i < len_positive; i++) {
if(arr[i] > 0) return i + 1;
}
return len_positive + 1;
}