find all pairs on integer array whose sum is equal to given number

Pattern: Hashing and frequency

medium

Count pairs of positions whose values add up to k, by counting how many earlier values are each element's partner.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of whole numbers and a number k. Count the pairs of positions i < j with nums[i] + nums[j] = k. Pairs at different positions count separately even when their values are the same. For example, [1, 5, 7, 1] with k = 6 has 2 pairs, and [1, 1, 1, 1] with k = 2 has 6. The count can be large, so it is returned as a 64-bit number.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. Many versions of it ask you to count the pairs rather than print them, and this guide counts. The function name countPairs is this guide's own.

Think first

  • How is this different from Two Sum, where exactly one pair existed?
  • When you reach x, how many pairs does it complete with the elements before it?
  • How many pairs are in [1, 1, 1, 1] with k = 2, and does your method count them all?

Hints

    Brute force, and why it fails

    Check every pair i < j: about n²/2 checks. It is correct, but slow for large arrays. Sorting with two pointers can count pairs in O(n log n), though repeated values need careful handling.

    The key insight

    It is Two Sum with a counter instead of an index: every earlier copy of the partner makes one more pair, so the map stores how many copies there have been.

    Dry run

    10 
    51 
    72 
    13 
    pairs0
    seen{}

    nums = [1, 5, 7, 1] and k = 6. The map counts how many times each value has appeared so far.

    Step 1 of 5

    The plan

    seen = empty map
    pairs = 0
    for x in nums:
        pairs = pairs + seen[k - x]        # 0 if missing
        seen[x] = seen[x] + 1
    return pairs
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One pass with average O(1) map operations.

    Edge cases

    • All values equal and 2x = k: n(n - 1)/2 pairs, so [1, 1, 1, 1] gives 6.
    • x equal to its own partner (as 3 with k = 6): it pairs only with earlier copies.
    • One element: 0 pairs.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long countPairs(int[] nums, int k) {
            Map<Integer, Integer> seen = new HashMap<>();      // value -> how many times seen so far
            long pairs = 0;
            for (int x : nums) {
                pairs += seen.getOrDefault(k - x, 0);          // each earlier partner makes one pair
                seen.put(x, seen.getOrDefault(x, 0) + 1);
            }
            return pairs;
        }
    }

    C++

    class Solution {
    public:
        long long countPairs(vector<int>& nums, int k) {
            unordered_map<int, int> seen;                      // value -> how many times seen so far
            long long pairs = 0;
            for (int x : nums) {
                auto found = seen.find(k - x);                 // each earlier partner makes one pair
                if (found != seen.end()) {
                    pairs += found->second;
                }
                seen[x]++;
            }
            return pairs;
        }
    };

    Python

    class Solution:
        def countPairs(self, nums, k):
            seen = {}                               # value -> how many times seen so far
            pairs = 0
            for x in nums:
                pairs += seen.get(k - x, 0)         # each earlier partner makes one pair
                seen[x] = seen.get(x, 0) + 1
            return pairs

    Common mistakes

    • Using a set instead of counts, which misses repeated partners.
    • Recording x before looking up, which counts a value paired with itself.
    • Counting each pair twice by looking both forwards and backwards.

    Similar problems