Flipkart Interview Question
SDE-2sCountry: India
Interview Type: Phone Interview
I will use a HashMap to match a pair of two numbers such that sum is K.
Iterate the unsorted array and for each number a, calculate b = k - a
If number b exists in the map, pair up those a and b and return the pair
otherwise put number a into the map and go on to next number in the array.
Once you go through the array, you can find all pairs that sum up to K.
I used two indices, s and e after sorting. Time complexity is O(n * log n). Space complexity is O(1).
static void printSum(int[] arr, int K) {
Arrays.sort(arr);
int s = 0;
int e = arr.length - 1;
while (s < e) {
if (arr[s] + arr[e] == K) {
System.out.println(arr[s] + ", " + arr[e]);
s++;
} else if (arr[s] + arr[e] > K) {
e--;
} else {
s++;
}
}
}
- Vir Pratap Uttam May 10, 2015