702779. Count pair sum

Basic

Count Pair Sum

Summary

The "Count pair sum" problem involves counting the number of pairs in an array that have a specific sum. This problem can be solved using various algorithms, including hash-based and sorting-based approaches.

Detailed Explanation

Given an array arr of size n, our goal is to find the number of pairs (i, j) such that arr[i] + arr[j] = targetSum. We will use a hash-based approach to solve this problem efficiently.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty hashmap sumCount to store the count of each sum in the array.
  2. Iterate through the array and calculate the sum of each pair (i, j) for all possible values of j. For each sum, increment the corresponding count in sumCount.
  3. Initialize a variable count to 0, which will store the total number of pairs that have the target sum.
  4. Iterate through the array again and check if the current element's index plus the count of the remaining elements in the array is equal to targetSum. If it is, increment count by the count of the remaining elements.
  5. Return the final value of count, which represents the number of pairs that have the target sum.

Time complexity: O(n) Space complexity: O(n)

Here's an ASCII art diagram illustrating the steps:

  arr = [1, 2, 3, 4, 5]
  
  // Initialize hashmap
  sumCount = {}
  
  // Iterate through array and calculate sums
  for i in range(len(arr)):
    for j in range(i+1, len(arr)):
      sum = arr[i] + arr[j]
      if sum not in sumCount:
        sumCount[sum] = 0
      sumCount[sum] += 1
  
  // Count pairs with target sum
  count = 0
  for i in range(len(arr)):
    remainingSum = targetSum - arr[i]
    if remainingSum in sumCount:
      count += sumCount[remainingSum]
  
  return count

Optimized Solutions

Java

View on GeeksforGeeks
public int countPairs(int[] arr, int targetSum) {
    Map<Integer, Integer> sumCount = new HashMap<>();
    for (int i : arr) {
        for (int j = i + 1; j < arr.length; j++) {
            int sum = i + j;
            sumCount.put(sum, sumCount.getOrDefault(sum, 0) + 1);
        }
    }
    int count = 0;
    for (int i : arr) {
        int remainingSum = targetSum - i;
        if (sumCount.containsKey(remainingSum)) {
            count += sumCount.get(remainingSum);
        }
    }
    return count;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.