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) - Returns true if there exists any pair of numbers whose sum is equal to value, otherwise returns false.

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
TwoSum Data Structure: Stream ProcessingInput Streamadd(1)add(3)add(2)find(4)Hash Map Storage1 → count: 13 → count: 12 → count: 1Query Resulttrue1 + 3 = 4O(1) addO(n) findEfficient streaming data structure with fast complement lookupsAdd: O(1) time, Find: O(n) time, Space: O(n)
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
Asked in
LinkedIn 15 Amazon 12 Google 8 Microsoft 6
35.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen