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
Two Sum III - Data Structure Design INPUT class TwoSum HashMap Storage: num: count 1: 1 3: 1 2: 1 Operations: TwoSum() add(1) add(3) add(2) find(4), find(7) ALGORITHM STEPS 1 Initialize Create empty HashMap 2 add(number) Store num with count 3 find(value) For each num in map: 4 Check Complement comp = value - num find(4) Logic: num=1: comp=3 exists? OK 1+3=4 --> true find(7) Logic: num=1: comp=6 exists? NO num=3: comp=4 exists? NO No pair found --> false FINAL RESULT Output Array: [null, null, null, null, true, false] Breakdown: TwoSum() null add(1) null add(3) null add(2) null find(4) true find(7) false 1+3=4 found, no pair=7 Key Insight: HashMap stores numbers with their counts for O(1) lookup. For find(value), check if complement (value - num) exists. Handle edge case when num equals complement by checking count > 1. Time: add() O(1), find() O(n) | Space: O(n) TutorialsPoint - Two Sum III - Data structure design | Hash Map Optimization
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