DSA using Apex (Salesforce)- 02/100
solving problems using apex inside salesforce!
Q: Given an array of integers
nums
and an integertarget
, return the two numbers such that they add up totarget
.You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order. If no pair exists, return an empty array.
Sample Input :
array : [3, 5, -4, 8, 11, 1, -1, 6]
Target sum : 10
Sample output : [-1,11]
This is one of the easy problems yet frequently asked one.
The brute force solution to the above problem will be to iterate over two loops and add every combination to check if it matches the target . With time complexity of O(N²).
What we are looking for is an optimal way to solve it in O(N) time complexity.
public class TwoNumberSum {
public static Integer[] doSum(Integer[] inputArr,Integer target){
Set<Integer> nums = new Set<Integer>();
for(Integer num :inputArr){
Integer potentialMatch = target-num;
if(nums.contains(potentialMatch)){
return new Integer[]{potentialMatch,num};
}else{
nums.add(num);
}
}
return new Integer[0];
}
}
There’s another way to solve it in O (nLog(n)) by sorting the array and then traversing using a while loop . That’s for some other day !
Thanks