I am working on an algorithm question in which I need to find out pair of number out of 2 sorted arrays which sum up to the given number. I need to print out the indexes of those pairs rather than number itself.
I have written an algorithm which does work but I am wondering is it the best solution or is there any better way to do it (complexity-wise).
/**
* Finds and prints all the pairs of indexes from 2 sorted arrays which sum up to the given number
* @param array1 The first array
* @param array2 The second array
* @param sum The number which needs to be constructed by summing integers of both arrays
*/
private static void findPairs(int[] array1, int[] array2, int sum) {
if(array1.length == 0 || array2.length == 0)
return;
Map<Integer, Integer> firstArrayMap = new HashMap<Integer, Integer>();
for(int i = 0; i < array1.length; i++) {
firstArrayMap.put(sum - array1[i], i);
}
for(int i = 0; i < array2.length; i++) {
if(firstArrayMap.containsKey(array2[i]))
System.out.println("Pair found at index : " + firstArrayMap.get(array2[i]) + " " + i);
}
}