Two Sum III - Data structure design Problem
Description
LeetCode Problem 170.
Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.
Implement the TwoSum class:
TwoSum()Initializes theTwoSumobject, with an empty array initially.void add(int number)Addsnumberto the data structure.boolean find(int value)Returnstrueif there exists any pair of numbers whose sum is equal tovalue, otherwise, it returnsfalse.
Example 1:
Input
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
Output
[null, null, null, null, true, false]
Explanation
TwoSum twoSum = new TwoSum();
twoSum.add(1); // [] --> [1]
twoSum.add(3); // [1] --> [1,3]
twoSum.add(5); // [1,3] --> [1,3,5]
twoSum.find(4); // 1 + 3 = 4, return true
twoSum.find(7); // No two integers sum up to 7, return false
Constraints:
-10^5 <= number <= 10^5-2^31 <= value <= 2^31 - 1- At most
10^4calls will be made toaddandfind.
Solution
Approach: Hash Map of Counts
Store how many times each number was added in a hash map count. Then add is a single O(1) update.
For find(value), try each distinct number x in the map as the first number of the pair. The second number would have to be y = value - x:
- If
yis not in the map,xcannot be part of a pair. - If
y != x, the pairx + yexists. - If
y == x, we need the same number twice, so its count must be at least2.
The last case is the catch. After add(3) alone, find(6) must be false, because one 3 cannot be used twice. After a second add(3) it becomes true.
This design makes add cheap and find linear. The other way around (store every pair sum on each add) makes find O(1) but add O(n), which is worse when there are many numbers. In Java and C++, value - x can go past the 32-bit range (for example value = -2^31), so we compute it as a 64-bit number.
Complexity: add is O(1) and find is O(n), where n is the number of distinct numbers added. O(n) space.
from collections import defaultdict
class TwoSum:
def __init__(self):
self.count = defaultdict(int) # number -> how many times it was added
def add(self, number: int) -> None:
self.count[number] += 1
def find(self, value: int) -> bool:
for x, c in self.count.items():
y = value - x
# x + x only counts when x was added at least twice
if y in self.count and (x != y or c > 1):
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)