![]() |
VOOZH | about |
Given an array arr[] and a target value, the task is to find all possible indices (i, j) of pairs (arr[i], arr[j]) whose sum is equal to target and i != j. We can return pairs in any order, but all the returned pairs should be internally sorted, that is for any pair(i, j), i should be less than j.
Examples:
Input: arr[] = {10, 20, 30, 20, 10, 30}, target = 50
Output: {{1, 2}, {1, 5}, {2, 3}, {3, 5}}
Explanation: All pairs with sum = 50 are:
- arr[1] + arr[2] = 20 + 30 = 50
- arr[1] + arr[5] = 20 + 30 = 50
- arr[2] + arr[3] = 30 + 20 = 50
- arr[3] + arr[5] = 20 + 30 = 50
Input: arr[] = {10, 20, 30, 20, 10, 30}, target = 80
Output: { }
Explanation: No pairs have sum = 80.
Table of Content
The simplest approach is to generate all possible pairs from the given array arr[] and if the sum of elements of the pairs is equal to target, then add it to the result.
1 2 1 5 2 3 3 5
The idea is to maintain a hash map with element as key and its indices as values. Iterate over the array and for each element arr[i], if (target - arr[i]) exists in the hash map, then pair i with all indices of (target - arr[i]) and store them in result.
In the worst case, this approach also takes O(n^2) time but in the average case, it is much faster than Naive approach as we are iterating over only those pairs whose sum is equal to target.
1 2 2 3 1 5 3 5