We can keep a map: {number -> count}. To find two numbers that sum up to value, we can iterate through the map. For x, (value – x) must be in the map. If x and (value – x) are equal, then the count of x must be at least 2.
Say, there are distinct numbers.
| Operation | Time | Space |
__init__ | ||
add | ||
find |
class TwoSum:
def __init__(self):
self.num_map = {}
def add(self, number: int) -> None:
if number not in self.num_map:
self.num_map[number] = 1
else:
self.num_map[number] += 1
def find(self, value: int) -> bool:
for x, count in self.num_map.items():
y = value - x
if x == y:
if count > 1:
return True
continue
if y in self.num_map:
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)
Leave a comment