Count Positive - Negative Pairs

Posted: 29 Jul, 2020
Difficulty: Easy


Try Problem

You have been given an array/list(ARR) of positive and negative integers. Print the number of pairs where:

arr[i] = -arr[j] and i != j
Given array/list can contain duplicate elements and will not contain '0'.

(arr[i],arr[j]) and (arr[j],arr[i]) are considered same.
Input format :
The first line of each test case contains an integers 'N' where 'N' denotes the size of array/list(ARR).

The next line contains 'N' space-separated integers representing array elements.
Output format :
Print the total number of positive-negative pairs present in the array/list.
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
Constraints :
1 <= N <= 10^5
-10^9 <= arr[i] <= 10^9

Time Limit: 1 sec
Approach 1
  • Initialize the totalPairs = 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] then increase the totalPairs by 1.
  • Return totalPairs.
Try Problem