Apex Coding Interview Challenge #6

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Solution

public List<Integer> productOfNumbers(List<Integer> intVals){
   List<Integer> productLst = new List<Integer>();
   for (Integer k = 0; k < intVals.size(); k++){
     Integer sumOfVals = 1; // it's 1 because multiplying by 0 will always be 0
     for (Integer j = 0; j < intVals.size(); j++){
      if (j != k){
        sumOfVals *= intVals.get(j);
      }
     }
    productLst.add(sumOfVals);
   }
  return productLst;
}

Test

System.debug(productOfNumbers(new List<Integer>{1, 2, 3, 4, 5})); //(120, 60, 40, 30, 24)

System.debug(productOfNumbers(new List<Integer>{3, 2, 1})); //(2, 3, 6)

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

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