Expedia Interview Question
Software Engineer / DevelopersHere's a solution using a hashmap to make the time complexity O(n)
private static void printNumsThatAddUpTo(int[] arr, int target) {
Map<Integer, Integer> storage = new HashMap<Integer,Integer>();
for (int i = 0; i < arr.length;i++){
if ( storage.containsKey(target - arr[i])){
if (!storage.containsKey(arr[i])){
System.out.println(arr[i]+ " "+(target - arr[i]));
storage.put(arr[i], arr[i]);
}
}else if (!storage.containsKey(arr[i])){
storage.put(arr[i], arr[i]);
}
}
}
1) sort the array
- nileshagarwal10 July 11, 20122) then start with one pointer i=0 and another j=n(array length)
3) calculate sum if greater then k then j-- and if less then k than i++
4) repeat 3 step till you find the sum or i>j