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)

2 Comments on “Apex Coding Interview Challenge #7”

  1. 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

  2. List x=new List{3,4,-1,7,1,2,5,6};
    Integer a;
    a=0;
    System.debug(x);
    do{
    a++;
    if(!x.contains(a)){
    break;
    }

    }while(true);
    System.debug(a);

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 )

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: