Count Unique Pairs for Target Sum
In many data analysis scenarios, identifying specific relationships between data points is crucial. Imagine you're processing transaction logs or analyzing product compatibility. You might need to find all distinct pairs of items that, when combined, meet a certain target value. This problem challenges you to efficiently count such unique pairs within a given dataset.
Given an array of integers nums and a target integer target, your task is to find the number of unique pairs (a, b) from nums such that a + b == target. A pair (a, b) is considered unique if the set of values {a, b} is distinct. For example, if nums = [1, 2, 1] and target = 3, the pair (1, 2) should only be counted once, even though 1 appears twice.
countUniquePairs that takes nums and target as input.target.nums correctly, counting each distinct value pair only once.nums: An array of integers. This array can contain positive, negative, or zero values, and may include duplicates.target: An integer representing the sum we are looking for.(a, b) from nums such that a + b == target.nums is empty or contains only one element, no pairs can be formed, so the function should return 0.nums = [2, 2, 4] and target = 4), then (2, 2) would form one unique pair. This means a and b in a + b = target refer to values, not necessarily distinct indices, but a and b must come from the nums array.{a, b} is the same as {b, a}. The count should reflect this uniqueness (e.g., (1, 2) and (2, 1) are considered the same unique pair).Examples
Example 1
Input:
nums = [1, 5, 3, 4, 2], target = 6
Output:
2
Note:
The unique pairs that sum to 6 are (1, 5) and (2, 4). The pair (3, 3) is not possible as 3 appears only once.
Example 2
Input:
nums = [1, 1, 2, 2], target = 3
Output:
1
Note:
The only unique pair that sums to 3 is (1, 2). Even though there are multiple ways to pick 1 and 2 from the array by index, the value pair {1, 2} is counted only once.
Example 3
Input:
nums = [0, 0, 0, 0], target = 0
Output:
1
Note:
The unique pair that sums to 0 is (0, 0). Since 0 appears multiple times, this pair is valid and counted once.
Example 4
Input:
nums = [-1, 0, 1, 2, -1], target = 0
Output:
2
Note:
The unique pairs are (-1, 1) and (0, 0). Note that -1 appears twice, but we only need one instance of each value for (-1,1) and 0 appears once so (0,0) is not possible unless 0 appears twice.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i], target <= 10^9Loading editor...