Two Sum III - Data structure design - Problem
Design a dynamic data structure that can efficiently handle a stream of integers and quickly determine if any pair of stored numbers sum to a target value.
You need to implement the TwoSum class with the following operations:
TwoSum()- Initializes an empty TwoSum objectvoid add(int number)- Adds a number to the data structureboolean find(int value)- Returnstrueif there exists any pair of numbers whose sum equalsvalue,falseotherwise
The challenge: Since numbers are added dynamically and searches happen frequently, you need to balance the efficiency of both operations. Consider the trade-offs between optimizing add vs find operations based on expected usage patterns.
Example:
TwoSum twoSum = new TwoSum(); twoSum.add(1); // [] becomes [1] twoSum.add(3); // [1] becomes [1,3] twoSum.add(5); // [1,3] becomes [1,3,5] twoSum.find(4); // return true (1 + 3 = 4) twoSum.find(7); // return false (no pair sums to 7)
Input & Output
example_1.py โ Basic Operations
$
Input:
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
โบ
Output:
[null, null, null, null, true, false]
๐ก Note:
TwoSum twoSum = new TwoSum(); twoSum.add(1); twoSum.add(3); twoSum.add(5); twoSum.find(4); // 1 + 3 = 4, return true; twoSum.find(7); // No pair sums to 7, return false
example_2.py โ Duplicate Numbers
$
Input:
["TwoSum", "add", "add", "add", "find", "find"]
[[], [3], [1], [3], [6], [3]]
โบ
Output:
[null, null, null, null, true, false]
๐ก Note:
After adding [3, 1, 3]: find(6) returns true (3 + 3 = 6 using two different 3's); find(3) returns false (would need 1.5 + 1.5, but we don't have 1.5)
example_3.py โ Edge Case with Same Number
$
Input:
["TwoSum", "add", "find", "add", "find"]
[[], [0], [0], [0], [0]]
โบ
Output:
[null, null, false, null, true]
๐ก Note:
With one 0, find(0) is false (need two 0's to sum to 0). After adding second 0, find(0) returns true (0 + 0 = 0)
Visualization
Tap to expand
Understanding the Visualization
1
Add Numbers
Store each number with its frequency in a hash map
2
Find Complement
For each stored number, check if its complement exists
3
Handle Duplicates
If complement equals the number, ensure we have at least 2 copies
Key Takeaway
๐ฏ Key Insight: Hash map with frequencies provides the optimal balance - O(1) additions and O(n) lookups, while correctly handling duplicate numbers for same-value pairs.
Time & Space Complexity
Time Complexity
O(1) add, O(n) find
Add is constant time hash insertion, find checks each unique number once
โ Linear Growth
Space Complexity
O(n)
Hash map stores at most n unique numbers with their frequencies
โก Linearithmic Space
Constraints
- -105 โค number โค 105
- -231 โค value โค 231 - 1
- At most 104 calls to add and find
- Each number can be added multiple times
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code