Count Pairs with Equal SumMedium

Count Pairs with Equal Sum

MediumPractice library · +20 XPhash mapcounting

Given a list of N integers, find the number of pairs (i, j) such that i < j and A[i] + A[j] = S for a given target sum S. Each integer can be used multiple times within a pair if it appears multiple times in the input list.

Input

The first line contains two integers N and S, the number of elements in the list and the target sum respectively. The second line contains N space-separated integers A_1, A_2, ..., A_N.

Output

Print a single integer, the total count of pairs (i, j) with i < j and A[i] + A[j] = S.

Constraints

1 <= N <= 200000, 0 <= A_i <= 10^9, 0 <= S <= 2*10^9.

Time limit 2 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
5 10
1 5 3 7 5
Output
2

Pairs are (1, 3) summing to 10 (A[1]+A[3] = 5+5=10) and (0, 3) summing to 10 (A[0]+A[3] = 3+7=10). Note that indices matter and the two 5s are distinct elements for pairing. The pairs of indices are (1, 4) and (2, 3).

Example 2

Input
4 6
2 4 2 4
Output
4

Pairs are (0, 1), (0, 3), (2, 1), (2, 3). All sum to 6.

Hints