Intermediate Level

Implement the method countPairsWithSum that counts index pairs whose values add up to a target.

Count pairs (i, j) where i < j and nums[i] + nums[j] == target.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size elements.
  • Duplicate values can create multiple valid index pairs.
  • Return the number of pairs, not the pairs themselves.
Example 1
Input:
nums (int[]) = [1,5,7,-1,5]
size (int) = 5
target (int) = 6
Return:
(int) 3
Example 2
Input:
nums (int[]) = [1,1,1,1]
size (int) = 4
target (int) = 2
Return:
(int) 6
Example 3
Input:
nums (int[]) = [2,4,3,5,7]
size (int) = 5
target (int) = 9
Return:
(int) 2

While scanning, add the number of earlier values equal to target - current, then record the current value.

Run your code to see the result.