Amazon Online Assessment (OA) - Two Sum - Unique Pairs

Given an int array nums and an int target, find how many unique pairs in the array such that their sum is equal to target. Return the number of pairs.

Examples

Example 1:

Input: nums = [1, 1, 2, 45, 46, 46], target = 47
Output: 2
Explanation:

1 + 46 = 47

2 + 45 = 47

Example 2:

Input: nums = [1, 1], target = 2
Output: 1
Explanation:

1 + 1 = 2

Example 3:

Input: nums = [1, 5, 1, 5], target = 6
Output: 1
Explanation:

[1, 5] and [5, 1] are considered the same.

Try it yourself

Solution

Prereq: Two sum

Explanation

Do a regular two sum but add a set to check for duplicates.

Implementation

1
1
from typing import List
2
2
3
3
def two_sum_unique_pairs(nums: List[int], target: int) -> int:
4
-
    # WRITE YOUR BRILLIANT CODE HERE
4
+
    seen = set()
5
-
    return 0
5
+
    complement = set()
6
+
    for num in nums:
7
+
        if target - num in complement:
8
+
            pair = (num, target - num) if num < target - num else (target - num, num)
9
+
            seen.add(pair)
10
+
        complement.add(num)
11
+
    return len(seen)
12
+
6
13
if __name__ == '__main__':
7
14
    nums = [int(x) for x in input().split()]
8
15
    target = int(input())
9
16
    res = two_sum_unique_pairs(nums, target)
10
17
    print(res)