875946. All distinct pairs with given sum

Easy

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:

  1. Initialize an empty hash table hash with default values (e.g., 0).
  2. Iterate through the array nums. For each element num, do the following:
    • Calculate the difference between the target sum target and the current element num: diff = target - num.
    • Check if diff is present in the hash table hash. If it is, add all pairs (i, j) such that nums[i] + nums[j] = diff to our result set.
  3. 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

View on GeeksforGeeks
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;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.