Suppose we want to make a data structure that has two methods −
We have to design this so that we can get the result on the fly. We will not search for numbers every time when a query comes.
So, if the input is like create an object obj and add few numbers 6, 14, 3, 8, 11, 15, then check like obj.find(9), obj.find(11), obj.find(15), then the output will be True, True, False as 9 can be formed with 6+3, 11 can be formed with 3+8. Now 15 is present in the data structure but no two numbers' sum is same as 15.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class PairSumChecker: def __init__(self): self.nums = set() self.multiple = set() def add(self, val): if val in self.nums: self.multiple.add(val) else: self.nums.add(val) def find(self, val): for n in self.nums: if n + n == val: return n in self.multiple elif val - n in self.nums: return True return False obj = PairSumChecker() obj.add(6) obj.add(14) obj.add(3) obj.add(8) obj.add(11) obj.add(15) print(obj.find(9)) print(obj.find(11)) print(obj.find(15))
print(obj.find(9)) print(obj.find(11)) print(obj.find(15))
True True False