/170. Two Sum Data Structure

170. Two Sum Data Structure

Easy
Arrays39.1% acceptance

Design a data structure that supports adding integers and finding if any pair of integers sums to a specified target value. Implement two methods: add(number: int) to store the number, and find(target: int) to check if there exists any pair of stored numbers whose sum equals the target value. Each method should be callable multiple times.

Example 1

Input: obj = TwoSum() obj.add(5) obj.add(7) obj.add(3) output1 = obj.find(12) output2 = obj.find(10)

Output: output1 = True output2 = False

Explanation: 5 + 7 = 12 exists; no pair sums to 10.

Example 2

Input: obj = TwoSum() obj.add(-2) obj.add(4) obj.add(6) output1 = obj.find(2) output2 = obj.find(8)

Output: output1 = True output2 = True

Explanation: -2 + 4 = 2; 4 + 4 = 8 (if 4 added twice, but here only once, so only 6 + 2 = 8 if 2 added, but not here, so output2 = False. Correction: output2 = False.

Constraints

  • The add and find methods can be called in any order.
  • The number of calls to add and find will not exceed 10^4.
  • Each number added will be an integer in the range [-10^9, 10^9].
  • The target value for find will be an integer in the range [-10^9, 10^9].
Python (current runtime)

Case 1

Input: obj = TwoSum() obj.add(10) obj.add(15) obj.add(-5) result1 = obj.find(5) result2 = obj.find(25)

Expected: result1 = True result2 = False

Case 2

Input: obj = TwoSum() obj.add(0) obj.add(0) obj.add(1) result1 = obj.find(0) result2 = obj.find(1)

Expected: result1 = True result2 = True

Case 3

Input: obj = TwoSum() obj.add(1000000000) obj.add(-1000000000) obj.add(0) result1 = obj.find(0) result2 = obj.find(1000000000)

Expected: result1 = True result2 = True