Count Positive - Negative Pairs

Easy
0/40
Average time to solve is 22m
profile
Contributed by
30 upvotes
Asked in companies
AtlassianAmazonAmdocs

Problem statement

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
Note:
Given array/list can contain duplicate elements and will not contain '0'.

(arr[i],arr[j]) and (arr[j],arr[i]) are considered same.
Detailed explanation ( Input/output format, Notes, Images )
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.
Note:
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
Sample Input 1:
9
-1 3 6 2 5 -4 3 2 -4
Sample Output 1:
0
 Explanation For Sample Input 1:
Since there doesn't exist any positive-negative pair, the Output is '0'.
Sample Input 2:
6
-2 8 2 5 -2 -5
Sample Output 2:
3
Hint

Try to explore every possible pair and check for the required condition.

Approaches (3)
Brute Force Approach
  • 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.
Time Complexity

O(N^2), where N is the size of the array.


As we are running two nested loops of size N.

Space Complexity

O(1)

 

As constant extra space, is used.

Code Solution
(100% EXP penalty)
Count Positive - Negative Pairs
Full screen
Console