875946. All distinct pairs with given sum
Here is the detailed Markdown blog post for the GeeksforGeeks problem "All distinct pairs with given sum":
All distinct pairs with given sum
Summary
Given an array nums and a target sum target, find all distinct pairs (i, j) such that nums[i] + nums[j] = target. This problem involves arrays and hash, requiring a combination of data structures and algorithmic thinking to solve.
Detailed Explanation
To approach this problem, we can use a hash table (or map) to store the elements in the array as keys and their indices as values. Then, for each element in the array, we check if the difference between the target sum and the current element is present in the hash table. If it is, we add the pair (i, j) to our result set.
Here's a step-by-step breakdown of the solution:
- Initialize an empty hash table
hashwith default values (e.g., 0). - Iterate through the array
nums. For each elementnum, do the following:- Calculate the difference between the target sum
targetand the current elementnum:diff = target - num. - Check if
diffis present in the hash tablehash. If it is, add all pairs(i, j)such thatnums[i] + nums[j] = diffto our result set.
- Calculate the difference between the target sum
- Return the list of distinct pairs.
Time complexity: O(n), where n is the length of the array nums.
Space complexity: O(n), since we need to store the hash table and the result set.
Here's an ASCII art diagram illustrating the algorithm:
+---------------+
| Hash Table |
+---------------+
|
|
v
+---------------+
| Iterate through |
| array nums |
+---------------+
|
|
v
+---------------+
| Calculate diff |
| and check hash |
+---------------+
Optimized Solutions
Java
import java.util.*;
public class Solution {
public List<List<Integer>> allPairs(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if (map.containsKey(diff)) {
for (int j : map.get(diff)) {
result.add(Arrays.asList(i, j));
}
}
map.put(nums[i], i);
}
return result;
}
}