Problem 241978 · medium · Level 02 Linear Data Structures

Count Pairs With a Target Sum

hash maps · pair counting · complements

Given a list of integers nums and an integer target, return how many index pairs (i, j) with i < j satisfy nums[i] + nums[j] == target.

Examples

Input:  nums = [1, 5, 1, 5, 3], target = 6
Output: 4
Explanation: pairs (0,1), (0,3), (1,2), (2,3) each sum to 6.

Input:  nums = [3, 3, 3], target = 6
Output: 3

Constraints

  • 0 <= len(nums) <= 10**5
  • -10**9 <= nums[i], target <= 10**9
  • Target complexity: O(n) time. Nested loops are too slow for the large tests.

Goals

  • Count complements seen so far instead of returning indices
  • Handle repeated values and the target/2 case correctly
Starting Python…