You are given an array of integers sorted in non-decreasing order and a target value. Count how many index pairs (i, j) with i < j satisfy nums[i] + nums[j] == target.
Equal values at different positions are considered distinct pairs. For example, in [2, 2, 2] with target 4 there are three pairs: (0,1), (0,2), and (1,2).
Line 1: two integers n and target separated by a space.
Line 2: n space-separated integers in non-decreasing order (this line is present even when n is small; if n == 0 it is empty).
A single integer: the number of valid index pairs.
Example 1
Input
5 6 1 2 2 3 4
Expected
2
Explanation
Sorted array [1,2,2,3,4], target 6. The pairs that sum to 6 are index pair (1,4) with values 2+4 and index pair (2,4) with values 2+4. No other pair reaches 6, so the answer is 2.
Example 2
Input
4 4 2 2 2 2
Expected
6
Explanation
Every pair of the four 2's sums to 4. There are C(4,2) = 6 index pairs, so the answer is 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 →