Problem 142328 · easy · Phase 01 Prerequisites & Setup

Count the Pairs

nested loops · lists · indexing

Write a function count_pairs(nums, target) that counts how many pairs of elements in nums add up to target.

A pair means two elements at different positions i and j with i < j. The same pair should be counted only once, so (nums[0], nums[1]) and (nums[1], nums[0]) are the same pair. Elements with equal values at different positions are different elements.

Examples

Input:  nums = [1, 2, 3, 4], target = 5
Output: 2
Explanation: 1 + 4 and 2 + 3.
Input:  nums = [1, 1, 1], target = 2
Output: 3
Explanation: Positions (0,1), (0,2) and (1,2) are three different pairs.
Input:  nums = [1, 2, 3], target = 10
Output: 0

Constraints

  • 0 <= len(nums) <= 50
  • -100 <= nums[i], target <= 100

Goals

  • Write one loop inside another and reason about which runs when
  • Use range(len(nums)) to loop over positions rather than values
  • Avoid counting the same pair twice by starting the inner loop after the outer index
Starting Python…