Skip to content

Commit b5c8c6a

Browse files
committed
added Two Sum - Unique Pairs
1 parent 0cc7ee0 commit b5c8c6a

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

Array/TwoSumUniquePairs/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Two Sum - Unique Pairs
2+
3+
[Leetcode Link](https://leetcode.com/discuss/interview-question/372434)
4+
5+
## Problem:
6+
7+
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.
8+
9+
## Example:
10+
11+
```
12+
Input: nums = [1, 1, 2, 45, 46, 46], target = 47
13+
Output: 2
14+
Explanation:
15+
1 + 46 = 47
16+
2 + 45 = 47
17+
```
18+
19+
```
20+
Input: nums = [1, 1], target = 2
21+
Output: 1
22+
Explanation:
23+
1 + 1 = 2
24+
```
25+
26+
```
27+
Input: nums = [1, 5, 1, 5], target = 6
28+
Output: 1
29+
Explanation:
30+
[1, 5] and [5, 1] are considered the same.
31+
```

Array/TwoSumUniquePairs/solution.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
def uniqueTwoSum(nums, target):
2+
numPairs = 0
3+
# sort array
4+
nums.sort()
5+
# two pointers from left-end and right-end
6+
left = 0
7+
right = len(nums)-1
8+
while left < right:
9+
# skip the same numbers (finding UNIQUE pairs)
10+
while left >= 1 and nums[left] == nums[left-1]:
11+
left += 1
12+
if left >= len(nums):
13+
break
14+
while right < len(nums)-1 and nums[right] == nums[right+1]:
15+
right -= 1
16+
if right < 0:
17+
break
18+
if left >= right:
19+
break
20+
if nums[left] + nums[right] == target:
21+
numPairs += 1
22+
left += 1
23+
right -= 1
24+
elif nums[left] + nums[right] > target:
25+
right -= 1
26+
else:
27+
left += 1
28+
return numPairs
29+
30+
31+
# simple test case
32+
nums = [1, 1, 2, 3, 4, 4, 43, 45, 45, 46, 46]
33+
target = 47
34+
print(uniqueTwoSum(nums, target))
35+
36+
# all dups
37+
nums = [1, 1, 1, 1, 1, 1, 1]
38+
target = 2
39+
print(uniqueTwoSum(nums, target))
40+
41+
# no two sum to target
42+
nums = [2, 3, 6, 2, 3]
43+
target = 7
44+
print(uniqueTwoSum(nums, target))
45+
46+
# unique
47+
nums = [1, 5, 1, 5]
48+
target = 6
49+
print(uniqueTwoSum(nums, target))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ Languages used: Java and Python
4848
- [Subarray Sum Equals K](Array/SubarraySumEqualsK)
4949
- [Sum Of Even Numbers After Queries](Array/SumOfEvenNumbersAfterQueries)
5050
- [Third Maximum Number](Array/ThirdMaximumNumber)
51+
- [Two Sum - Unique Pairs](Array/TwoSumUniquePairs)
5152

5253
### [Bit Manipulation](./BitManipulation)
5354

0 commit comments

Comments
 (0)