Count Pairs With Given Sum — Easy Problem & Solution
Given an array arr and an integer target, count the pairs of indices (i, j) with i < j and arr[i] + arr[j] == target.
- Difficulty: Easy
- Topics: Arrays, Hash Table
- Asked at: Amazon, TCS, Wipro, Zoho
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an array arr and an integer target, count the pairs of indices (i, j) with i < j and arr[i] + arr[j] == target.
Pairs are counted by position, so repeated values contribute several pairs.
Example 1
Input: arr = [1,5,7,-1,5], target = 6
Output: 3
Explanation: (1,5), (7,-1) and (1,5) again with the second 5.
Example 2
Input: arr = [1,1,1,1], target = 2
Output: 6
Explanation: Every one of the six index pairs sums to 2.
Example 3
Input: arr = [10,12,10,15,-1], target = 125
Output: 0
Constraints
1 <= arr.length <= 100000-100000 <= arr[i] <= 100000-200000 <= target <= 200000
How to solve Count Pairs With Given Sum
For each element, the partner it needs is fixed: target - x. Keeping a running tally of everything seen so far turns the search for partners into a single lookup.
Approach
- Keep a map from value to how many times it has appeared so far.
- For each
x, addseen[target - x](zero if absent) to the answer. - Then increment
seen[x]and continue.
Why it works
Counting before inserting means every pair is attributed exactly once — at its later index — so no pair is double counted and no element pairs with itself. Repeated values are handled naturally because the map stores counts, not just presence.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- Inserting
xbefore the lookup makesxits own partner whenever2x == target. - Using a set instead of a count map reports
[1,1,1,1]as one pair rather than six.
Reference solution
Python
from typing import List
def countPairsWithSum(arr: List[int], target: int) -> int:
seen = {}
total = 0
for x in arr:
total += seen.get(target - x, 0)
seen[x] = seen.get(x, 0) + 1
return totalJavaScript
var countPairsWithSum = function(arr, target) {
var seen = {}, total = 0;
for (var i = 0; i < arr.length; i++) {
var need = String(target - arr[i]);
if (seen[need] !== undefined) total += seen[need];
var key = String(arr[i]);
seen[key] = (seen[key] === undefined ? 0 : seen[key]) + 1;
}
return total;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.