Apex Coding Interview Challenge #2

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?

Solution

public Boolean checkNumberAddToK(List<Integer> intVals, Integer k){
   Boolean sumAddsUpFlag = false;
   Set<Integer> diffVals = new Set<Integer>();
   for (Integer intVal : intVals){
     if (diffVals.isEmpty()){
       diffVals.add(k-intVal);
     } else {
       if (diffVals.contains(intVal)){
         sumAddsUpFlag = true;
         break; 
       } else {
         diffVals.add(k-intVal);
       }
     }
   }

   return sumAddsUpFlag;
}

Test

System.debug(checkNumberAddToK(new List{10, 15, 3, 7}, 17)); //return true

System.debug(checkNumberAddToK(new List{10, 15, 3, 8}, 17)); //return false

Complexity Analysis
Time complexity: O(n)
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 )

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: