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
Returns (int) 3

Example 2

Input
nums (int[]) = [1,1,1,1]
size (int) = 4
target (int) = 2
Returns (int) 6

Example 3

Input
nums (int[]) = [2,4,3,5,7]
size (int) = 5
target (int) = 9
Returns (int) 2

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

Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.