New update is available. Click here to update.

Last Updated: 29 Jul, 2020

Difficulty: Easy

```
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.
```

```
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.
```

```
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.
```

```
1 <= N <= 10^5
-10^9 <= arr[i] <= 10^9
Time Limit: 1 sec
```

We can observe that the sum of the two elements is 0 when they make a positive-negative pair.

- Sort the array and take two pointers
**i**and**j**, one pointer pointing to the start of the array i.e.**i = 0,**and another pointer pointing to the end of the array i.e.**j = n – 1**. If**arr[i] + arr[j]**- Is greater than the
**0**then decrements**j**. - Lesser than the
**0**then increments**i**. - Equals the
**0**then count such pairs.

- Is greater than the
- To count the pairs when arr[i] + arr[j] = 0
- Count number of elements equal to the arr[i]
- Count number of elements equal to the arr[j]
- Then totalPairs will be increased by the product of the count of elements equal to arr[i] and the count of elements equal to arr[j].

- Create a hashmap/dictionary which will store the count of occurrences of each element and initially it will be empty.
- Run a loop from i=0 to N-1 and for each i’th element its value is arr[i] and we need to find the number which is equal to
**- arr[i].**So check if -arr[i] is present in the hashmap/dictionary if it is present, the answer will be increased by the count of occurrence of -arr[i] present in the hashmap/dictionary as arr[i] can be paired with all those elements equal to -arr[i] present in its left side. - Now increase the count of arr[i] in the hashmap/dictionary by 1.

SIMILAR PROBLEMS

Merge Two Sorted Arrays Without Extra Space

Posted: 19 Nov, 2022

Difficulty: Moderate

Ninja And The Strictly Increasing Array

Posted: 27 Nov, 2022

Difficulty: Moderate

Maximum GCD

Posted: 8 Dec, 2022

Difficulty: Hard

Negative To The End

Posted: 16 Dec, 2022

Difficulty: Easy

Sort 0s, 1s, 2s

Posted: 24 Dec, 2022

Difficulty: Easy

Popular Interview Problems: