# Apex Coding Interview Challenge #7

Given an array of integers, find the first missing positive integer in linear time and constant space. 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.

For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.

Solution

```public Integer lowestIntMissingFromLst(List<Integer> intVals){
Integer missingNum = 0;
Integer maxVal = 0;
Integer maxMin = 0;
Integer maxMax = 0;
for (Integer k = 0; k < intVals.size(); k++){
if (k == 0){
maxVal = intVals.get(k);
} else if (maxVal < intVals.get(k)){
maxVal =  intVals.get(k);
maxMin = intVals.get(k) - intVals.size();
maxMax = intVals.get(k) + intVals.size();
}

Integer plusOne = intVals.get(k)+1;
Integer minusOne = intVals.get(k)-1;

if (plusOne < maxMax && !intVals.contains(plusOne)){
missingNum = plusOne;
} else if (minusOne < maxMin && !intVals.contains(minusOne)){
missingNum = minusOne;
}
}
return missingNum;
}
```

Test

```System.debug(lowestIntMissingFromLst(new List<Integer>{3, 4, -1, 1})); //2

System.debug(lowestIntMissingFromLst(new List<Integer>{1, 2, 0})); //3
```

Complexity Analysis
Time complexity: O(n)
Space complexity: O(1)

### 1 Comments on “Apex Coding Interview Challenge #7”

1. Vivek

Hi Michel,

May I know how you have calculated Maxmin and Maxmax and why you have used the size of the list to calculate?

If I use this list [300,-1,3,100,-15], would this still work?

Thanks,
Vivek