The problem is the one explained in Given an unsorted integer array, find the first missing positive integer
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
return3
,
and[3,4,-1,1]
return2
.Your algorithm should run in \$O(n)\$ time and use constant space.
I am trying to learn Java 8+ and wrote the following code. Request any improvisations possible.
int firstPositive(int[] inputArray) {
//Convert all negative numbers to 0.
IntStream.range(0, inputArray.length).forEach(idx -> {
if (inputArray[idx] < 0) inputArray[idx] = 0;
});
IntStream.range(0, inputArray.length).forEach(idx -> {
if (Math.abs(inputArray[idx]) == 0) {
inputArray[0] = -Math.abs(inputArray[0]);
}
else if (Math.abs(inputArray[idx]) - 1 < inputArray.length && inputArray[Math.abs(inputArray[idx]) - 1] > 0) {
inputArray[Math.abs(inputArray[idx]) - 1] *= -1;
}
});
OptionalInt res = IntStream.range(0, inputArray.length).filter(idx -> inputArray[idx] >= 0).findFirst();
if (res.isPresent()) {
return res.getAsInt()+1;
}
return inputArray.length+1;
}