Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to create data structure to check pair sum is same as value in Python
Sometimes we need to build a data structure that efficiently checks if any two elements sum to a target value. This problem requires designing a class with two methods: add() to insert values and find() to check pair sums.
Problem Statement
We need to create a data structure with two operations ?
-
add(val)− adds the value to the data structure -
find(val)− checks whether there are two elements whose sum equals val
The key requirement is efficiency − we should be able to answer queries quickly without searching through all numbers every time.
Example Scenario
If we add numbers 6, 14, 3, 8, 11, 15 and then query ?
-
find(9)returnsTrue(6 + 3 = 9) -
find(11)returnsTrue(3 + 8 = 11) -
find(15)returnsFalse(15 exists but no two numbers sum to 15)
Solution Approach
We use two sets to track numbers efficiently ?
-
nums− stores unique numbers -
multiple− tracks numbers that appear more than once
This allows us to handle cases where the same number appears twice (like finding 6 + 6 = 12).
Implementation
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
# Test the implementation
obj = PairSumChecker()
obj.add(6)
obj.add(14)
obj.add(3)
obj.add(8)
obj.add(11)
obj.add(15)
print(obj.find(9)) # 6 + 3 = 9
print(obj.find(11)) # 3 + 8 = 11
print(obj.find(15)) # No pair sums to 15
True True False
How It Works
Adding Numbers:
- If the number already exists in
nums, add it tomultiple - Otherwise, add it to
nums
Finding Pairs:
- For each number
n, check ifval - nexists innums - Special case: if
n + n = val, ensurenappears multiple times
Example with Duplicates
obj = PairSumChecker() obj.add(5) obj.add(5) # Now 5 appears twice obj.add(10) print(obj.find(10)) # 5 + 5 = 10, True print(obj.find(15)) # 5 + 10 = 15, True print(obj.find(20)) # No pair sums to 20, False
True True False
Time Complexity
-
add(val): O(1) average case for set operations -
find(val): O(n) where n is the number of unique elements
Conclusion
This solution uses two sets to efficiently track numbers and their duplicates. The find() method checks all possible pairs by iterating through stored numbers and looking up their complements in constant time.
