Two Sum III - Data structure design — LeetCode 170 Python Solution

EasyLeetCode PremiumDesignArrayHash TableTwo PointersData Stream
Problem
#170
Reading time
4 min

The problem

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.

Example

Input
["TwoSum", "add", "add", "add", "find", "find"]
Output
[null, null, null, null, true, false]
Explanation
TwoSum twoSum = new TwoSum();

Python solution

Python
class TwoSum:

    def __init__(self):
        self.cnt = defaultdict(int)

    def add(self, number: int) -> None:
        self.cnt[number] += 1

    def find(self, value: int) -> bool:
        for x, v in self.cnt.items():
            y = value - x
            if y in self.cnt and (x != y or v > 1):
                return True
        return False


# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 170. Two Sum III - Data structure design is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 170. Two Sum III - Data structure design?
LeetCode 170. Two Sum III - Data structure design is rated Easy on LeetCode.
What is the time complexity of LeetCode 170. Two Sum III - Data structure design?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 170. Two Sum III - Data structure design?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 170. Two Sum III - Data structure design cover?
LeetCode 170. Two Sum III - Data structure design is tagged Design, Array, Hash Table, Two Pointers and Data Stream on LeetCode.
Is LeetCode 170. Two Sum III - Data structure design a premium problem?
Yes. LeetCode 170. Two Sum III - Data structure design is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview