Count Distinct Pairs With Sum K
Updated
Problem statement
You are given an integer array nums and an integer k.
Count the pairs of values {a, b} with a + b == k, where a and b are taken from two different positions of nums. Pairs are compared by their values, not by their positions, and order does not matter: {a, b} and {b, a} are the same pair, and a pair is counted once however many times its values appear. A pair {a, a} needs a to appear at least twice.
Return the number of distinct pairs whose sum equals k.
Function
countDistinctPairs(nums: int[], k: int) → intExamples
Example 1
nums = [3,1,4,1,5,9,2,6]k = 7return = 3The distinct pairs are {1, 6}, {2, 5} and {3, 4}. The value 1 appears twice, so 1 + 6 can be made from two different positions of 1, but it is still the one pair {1, 6} and counts once. 9 would need -2, which is not in the array.
Example 2
nums = [5,-2,5,3,7,3]k = 10return = 2The distinct pairs are {3, 7} and {5, 5}. The pair {5, 5} counts because 5 appears at two different positions. 3 also appears twice, but {3, 7} is counted once. -2 would need 12, which is not in the array.
Example 3
nums = [6,1,2]k = 12return = 06 + 6 = 12, but 6 appears only once, and a pair needs two different positions. No other two numbers add up to 12, so the answer is 0.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= k <= 10^9
More eBay Onsite Interview questions
- Extract Hashtags from a TweetONSITE INTERVIEW · Seen Nov 2026
- Validate Ada Integer LiteralONSITE INTERVIEW · Seen Nov 2026
- Diameter of Binary TreeONSITE INTERVIEW · Seen Nov 2026
- Count Staircases with Strictly Increasing StepsONSITE INTERVIEW · Seen Oct 2026
- Hierarchical Permission CheckONSITE INTERVIEW · Seen Oct 2026
- Matrix MultiplicationONSITE INTERVIEW · Seen Oct 2026
- N-Queens Solution CountONSITE INTERVIEW · Seen Oct 2026
- Gas StationONSITE INTERVIEW · Seen Oct 2026
- Onion-Peel Layers of a Binary TreeONSITE INTERVIEW · Seen Oct 2026
- Container With Most WaterONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- List the Key and Value of Every Map EntryNewgen Software · ONSITE INTERVIEW
- Pizza Price CalculatorMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Cross-Day User Trust ScoresAffirm · PHONE SCREEN · ONSITE INTERVIEWAffirm interview questions
- Map and Accumulate Learning QueriesPalantir · ONSITE INTERVIEWPalantir interview questions
- Filter Pins by Excluded IDsPinterest · ONSITE INTERVIEWPinterest interview questions
- Best Average Student ScoreGoldman Sachs · PHONE SCREEN · ONSITE INTERVIEWGoldman Sachs interview questions
- Longest Dictionary Word from Nine LettersGoogle · ONSITE INTERVIEWGoogle interview questions
- Two SumOptimus Information · ONSITE INTERVIEWOptimus Information interview questions
- Keep the First Key for Each Distinct ValueOneTrust · ONSITE INTERVIEW
- Two Positions That Add Up to a TargetDocuSign · PHONE SCREEN · ONSITE INTERVIEWDocuSign interview questions