Count Pairs with Sum

Easy~15 min

Given an array of integers nums and a target integer target, count the number of pairs (i, j) where i < j such that nums[i] + nums[j] == target.

Use a brute-force nested loop approach: check every possible pair.

For example, given nums = [1, 2, 3, 4, 5] and target = 5, the valid pairs are (0, 3) giving 1 + 4 = 5 and (1, 2) giving 2 + 3 = 5, so the answer is 2.

Examples

Example 1
Input: nums = [1, 2, 3, 4, 5], target = 5
Output: 2
Explanation: Pairs: (1,4) and (2,3) both sum to 5.
Example 2
Input: nums = [1, 1, 1], target = 2
Output: 3
Explanation: All three pairs (0,1), (0,2), (1,2) sum to 2.
Example 3
Input: nums = [1, 2, 3], target = 10
Output: 0
Explanation: No pair sums to 10.

Constraints

  • 2 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6
  • -10^6 <= target <= 10^6
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run