Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created October 9, 2020 06:04
Show Gist options
  • Select an option

  • Save kuntalchandra/dec7dd77702201233744f646926f82c2 to your computer and use it in GitHub Desktop.

Select an option

Save kuntalchandra/dec7dd77702201233744f646926f82c2 to your computer and use it in GitHub Desktop.
Two Sum III - Data structure design
"""
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 the TwoSum object, with an empty array initially.
void add(int number) Adds number to the data structure.
boolean find(int value) Returns true if there exists any pair of numbers whose sum is equal to value, otherwise, it returns false.
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
"""
from bisect import bisect_left
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
idx = bisect_left(self.stack, number)
self.stack.insert(idx, number)
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
low, high = 0, len(self.stack) - 1
while low < high:
if self.stack[low] + self.stack[high] > value:
high -= 1
elif self.stack[low] + self.stack[high] < value:
low += 1
else:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment