Program to create data structure to check pair sum is same as value in Python


Suppose we want to make a data structure that has two methods −

  • add(val) this adds the value val to the data structure
  • find(val) this checks whether there are two elements whose sum is val or not

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 −

  • Define the constructor.
  • nums := a new set
  • multiple := a new set
  • Define a function add(). This will take val
    • insert val into multiple
  • otherwise,
    • insert val into nums
  • Define a function find() . This will take val
  • for each n in nums, do
    • if n + n is same as val, then
      • return true when n is in multiple
    • otherwise when val - n is in nums, then
      • return True
  • return False

Example

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))

Input

print(obj.find(9))
print(obj.find(11))
print(obj.find(15))

Output

True
True
False

Updated on: 14-Oct-2021

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements