You are given an array/list βARRβ consisting of βNβ distinct integers arranged in ascending order. You are also given an integer βTARGETβ. Your task is to count all the distinct pairs in βARRβ such that their sum is equal to βTARGETβ.
Note:
1. Pair (x,y) and Pair(y,x) are considered as the same pair.
2. If there exists no such pair with sum equals to 'TARGET', then return -1.
Example:
Let βARRβ = [1 2 3] and βTARGETβ = 4. Then, there exists only one pair in βARRβ with a sum of 4 which is (1, 3). (1, 3) and (3, 1) are counted as only one pair.
The first line of input contains an integer βTβ which denotes the number of test cases.
The first line of each test case contains two single space-separated integers βNβ and βTARGETβ representing the number of elements in the array/list βARRβ and the required pair-sum respectively.
The next line of each test case contains βNβ single space-separated integers denoting the elements of βARRβ.
Output Format :
For each test case, return the numbers of pairs in βARRβ whose sum is equal to βTARGETβ.
Note:
You don't need to print anything, it has already been taken care of. Just implement the given function.
1 <= βTβ <= 100
2 <= βNβ <= 5000
1 <= βARR[i]β, βTARGETβ <= 10^5
Where ARR[i]β represents the elements of array/list βARRβ.
Time Limit: 1 sec
2
5 6
1 2 3 4 5
6 7
1 2 3 4 5 6
2
3
In test case 1, there exist only 2 pairs whose sum is equal to βTARGETβ i.e (1, 5) and (2, 4).
In test case 2, there are 3 pairs whose sum is equal to βTARGETβ which are (1, 6), (2, 5), and (3, 4).
2
4 10
1 3 5 6
5 12
1 3 6 9 11
-1
2
In test case 1, there is not a pair whose sum is equal to βTARGETβ. So we return -1.
In test case 2, there are 2 pairs whose sum is equal to βTARGETβ, (1, 11) and (3, 9) respectively.
Try to traverse through every pair possible.
First, we declare a variable 'COUNTPAIRβ in which we store all pairs whose sum is equal to 'TARGETβ. Then, we traverse the array βARRβ and assume every element as the first element of the pair. Then we again traverse the remaining array and consider every element as a second element of the pair, and check whether the sum of the two elements is equal to 'TARGET' or not. If it is equal to 'TARGET',β then we increase our βCOUNTPAIRβ by 1.
The steps are as follows:
O(N ^ 2), Where βNβ represents the number of elements in the array/list βARRβ.
Since we are using two nested loops for finding a pair, thus the time complexity will be O(N ^ 2).
O(1).
Since we are not using any extra space for finding our resultant answer. Thus the space complexity will be O(1).