Number Of Pairs With Given Sum

Posted: 29 Jul, 2020
Difficulty: Moderate


Try Problem

You have been given an integer array/list(arr) and a number 'Sum'. Find and return the total number of pairs in the array/list which when added, results equal to the 'Sum'.

Given array/list can contain duplicate elements.

(arr[i],arr[j]) and (arr[j],arr[i]) are considered same.
Input format :
The first line contains 2 space-separated integers N and Sum.

The next line contains N space-separated integers representing array elements.
Output format :
Print the total number of pairs present in the array/list.
Constraints :
1 <= N <= 10^5
-10^4 <= Sum <= 10^4
-10^4 <=  arr[ i ] <= 10^4

Time Limit: 1 sec
Approach 1
  • Initialize the ans = 0
  • Run two loops first from i = 0 to n-1 and second from j = i+1 to  n-1 and if arr[i] + arr[j] == Sum then increase the ans by 1.
  • Return ans
Try Problem