I was working on a practice Java exam online:
Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null. For example, findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12) should return a single dimensional array with two elements and contain any of the following pairs of indices:
1 and 4 (3 + 9 = 12) 2 and 3 (5 + 7 = 12) 3 and 2 (7 + 5 = 12) 4 and 1 (9 + 3 = 12)
Here is my solution:
public class TwoSum {
public static int[] findTwoSum(int[] list, int sum) {
int[] twoSum = null;
if(list != null){
int listSize = list.length;
int mod = listSize % 2;
int half = listSize/2;
int stop = mod > 0 ? half+1 : half;
if(listSize >= 2){
outer: for(int currentIndex=0; currentIndex<listSize; currentIndex++){
if(currentIndex == stop){
break;
}
for(int otherIndex=0; otherIndex<listSize; otherIndex++){
if(currentIndex < otherIndex){
int current = list[currentIndex];
int other = list[otherIndex];
int currentSum = current + other;
if(currentSum == sum){
twoSum = new int[]{currentIndex, otherIndex};
break outer;
}
}
}
}
}
}
return twoSum;
}
public static void main(String[] args) {
int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12);
System.out.println(indices[0] + " " + indices[1]);
}
}
My code passed all the unit tests, however, they have another check for a large list, and apparently my code runs too slow when the list size grows. Apart from me trying to decipher what their definition of too slow is, simply put, are there any optimizations I can make to have my code run faster? I tried to find the 'tipping point' in comparing numbers where I could stop checking, and I added that optimization, but apparently, that isn't good enough.