You are given an integer array a of length n and an integer target. Count the number of pairs of positions (i, j) with i < j such that a[i] + a[j] == target.
Equal values at different positions are counted as distinct pairs — for example, in [0, 0, 0] with target 0 there are three valid pairs of positions.
Line 1: two integers n and target, separated by a space.
Line 2: n space-separated integers a[0] … a[n-1]. If n == 0, this line is empty or absent.
A single integer: the number of position pairs (i, j) with i < j and a[i] + a[j] == target.
Example 1
Input
5 6 1 5 3 3 2
Expected
2
Explanation
Pairs summing to 6: positions (0,1) give 1+5=6, and (2,3) give 3+3=6. No other pair sums to 6, so the answer is 2.
Example 2
Input
4 0 0 0 0 0
Expected
6
Explanation
Every pair of the four zeros sums to 0. The number of position pairs is C(4,2) = 6.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →