Positive Negative Pair

Easy
0/40
Average time to solve is 10m
profile
Contributed by
18 upvotes
Asked in companies
SamsungGrowwOptum

Problem statement

Given an array of distinct integers, find all the pairs having positive value and negative value of a number that exists in the array. Return the pairs in any order.

Note:
The pair consists of equal absolute values, one being positive and another negative.

Return an empty array, if no such pair exists.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The next ‘2T’ lines represent the ‘T’ test cases.

The first line of each test case contains an integer ‘N’ denoting the number of integers in the array. 

The second line of each test case contains ‘N’ space-separated integers which denote the elements of the array.
Output Format:
For each test case, print all pairs with equal absolute value with one being positive and another negative. 
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
1 <= N <= 10^4
-10^5 <= A[i] <= 10^5

Time Limit: 1 second
Sample Input 1:
2
2
-2 2
2
1 2
Sample Output 1:
-2 2
Explanation For Sample Output 1:
Test case 1:
In the first test case, we can see that the absolute values of -2 and 2 are the same. But their signs are different(positive and negative). So that’s our answer. 

Test case 2:
There is no number present in the array with both positive and negative values. 
Sample Input 2:
2
6
1 -3 2 3 6 -1
8
4 8 9 -4 1 -1 -8 -9
Sample Output 2:
-1 1 -3 3
-1 1 -4 4 -8 8 -9 9
Hint

Try to do as asked in the problem and simply check for every integer if both positive and negative values are present or not.

Approaches (3)
Brute Force Approach
  • We use two nested loops to find the solution.
  • We make a vector to store positive and negative pairs.
  • For each element arr[i], find the corresponding negative of arr[i] from index ‘i + 1’ to ‘n – 1’ and store it in another array.
  • Return the answer vector.
Time Complexity

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

 

Here we are nesting two loops, one is going from 1 to N, and the second is going from ‘i+1’ to N for every ‘i’ in the first loop.

Space Complexity

O(N), where ‘N’ is the size of the array.

 

In the worst case, when every number has a negative-positive value, the output array takes space of order ‘N’.

Code Solution
(100% EXP penalty)
Positive Negative Pair
Full screen
Console