VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-with-given-sum/

⇱ 2 Sum - Count pairs with given sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

2 Sum - Count pairs with given sum

Last Updated : 6 Aug, 2025

Given an array arr[] of n integers and a target value, find the number of pairs of integers in the array whose sum is equal to target.

Examples:

Input: arr[] = [1, 5, 7, -1, 5], target = 6
Output:  3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5).         

Input: arr[] = [1, 1, 1, 1], target = 2
Output:  6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1) and (1, 1).

Input: arr[] = [10, 12, 10, 15, -1], target = 125
Output:  0
Explanation: There is no pair with sum = target

[Naive Approach] By Generating all Possible Pairs - O(n^2) time and O(1) space

The very basic approach is to generate all the possible pairs and check if any pair exists whose sum is equals to given target value, then increment the count variable.


Output
3

[Better Approach] Using Two Pointers Technique - O(nlogn) Time and O(1) Space

The idea is to sort the input array and use two-pointer technique. Maintain two pointers, say left and right and initialize them to the first and last element of the array respectively. According to the sum of left and right pointers, we can have three cases:

  • arr[left] + arr[right] < target: Increase the pair sum by moving the left pointer towards right.
  • arr[left] + arr[right] > target: Decrease the pair sum by moving the right pointer towards left.
  • arr[left] + arr[right] = target: We have found a pair whose sum is equal to target. We can find the product of the count of both the elements and add them to the result.

Output
3

[Expected Approach] Using Hash Map or Dictionary - O(n) Time and O(n) Space

HashMap or Dictionary provides a more efficient solution to the 2Sum problem. Instead of checking every pair of numbers, we keep each number in a map as we go through the array. For each number, we calculate its complement (i.e., target - current number) and check if it’s in the map. If it is, increment the count variable by the occurrences of complement in map.


Output
3

Related Problems:

Comment