Two Sum III - Data structure design - 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.void add(int number)- Adds number to the data structure.boolean find(int value)- Returnstrueif there exists any pair of numbers whose sum is equal to value, otherwise returnsfalse.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["TwoSum", "add", "add", "add", "find", "find"], values = [null, 1, 3, 2, 4, 7]
›
Output:
[null, null, null, null, true, false]
💡 Note:
Initialize TwoSum, add numbers 1, 3, 2. find(4) returns true because 1+3=4. find(7) returns false because no pair sums to 7.
Example 2 — Duplicate Numbers
$
Input:
operations = ["TwoSum", "add", "add", "find"], values = [null, 2, 2, 4]
›
Output:
[null, null, null, true]
💡 Note:
Add 2 twice, then find(4) returns true because 2+2=4. Need to handle duplicate numbers correctly.
Example 3 — No Valid Pair
$
Input:
operations = ["TwoSum", "add", "add", "find"], values = [null, 1, 5, 3]
›
Output:
[null, null, null, false]
💡 Note:
Add 1 and 5, then find(3) returns false because no combination of 1 and 5 equals 3.
Constraints
- -105 ≤ number ≤ 105
- -2×105 ≤ value ≤ 2×105
- At most 104 calls to add and find
Visualization
Tap to expand
Understanding the Visualization
1
Stream Input
Numbers arrive one by one via add() calls
2
Store Efficiently
Hash map tracks numbers and frequencies
3
Fast Lookup
find() checks complements in O(1) time
Key Takeaway
🎯 Key Insight: Use hash map to store frequencies and enable O(1) complement lookups for efficient pair detection
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code