Magicsheet logo

Two Sum III - Data structure design

Easy
50%
Updated 6/1/2025

Two Sum III - Data structure design

What is this problem about?

The "Two Sum III coding problem" focuses on class design and performance trade-offs. You need to build a system that can store numbers as they arrive in a stream and, at any moment, check if there is a pair in the stream that sums to a specific value. This is a classic "API Design" challenge that asks you to optimize for either the "Write" (add) or "Read" (find) operation.

Why is this asked in interviews?

LinkedIn and Amazon ask this question to see how you handle "Conflicting Constraints." In a real-world system, you might have millions of data points added but only a few queries, or vice-versa. Your choice of internal data structure (a sorted list vs. a hash map) tells the interviewer how you evaluate system requirements. It's an excellent way to see your "System Design" instincts applied to a small-scale algorithmic problem.

Algorithmic pattern used

The "Data Stream, Array, Hash Table, Design, Two Pointers interview pattern" centers on the Hash Map.

  • add(number): Store the number in a Hash Map, incrementing its frequency count. (O(1)O(1) time).
  • find(value): Iterate through the keys in the map. For each key k, check if value - k is also a key in the map. Special care is needed if k == value - k (need frequency >= 2). (O(N)O(N) time where NN is unique elements).

Example explanation

  1. add(5), add(2), add(5) -> Map: {5: 2, 2: 1}
  2. find(10):
    • Check key 5: Need 10-5 = 5. Since frequency of 5 is 2, return true.
  3. find(8):
    • Check key 5: Need 8-5 = 3. No.
    • Check key 2: Need 8-2 = 6. No.
    • Return false.

Common mistakes candidates make

The most common mistake is attempting to pre-calculate all possible sums in the add step. If you have NN numbers, there are O(N2)O(N^2) possible sums, which would consume massive amounts of memory. Another mistake is not handling the "duplicate number" case correctly, where a sum requires two instances of the same value.

Interview preparation tip

For the "Two Sum III interview question," be ready to discuss the trade-offs. If the find operation is extremely frequent, you might suggest keeping the array sorted and using two pointers, or using a balanced BST. Demonstrating that you have multiple "tools in your belt" is what interviewers are looking for.

Similar Questions