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)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: