Two Sum III - Data structure design

add/find with frequency map — find scans entries and checks complement, doubling check for x+x = target.

Easy
Time O(1) add Space O(n)
LeetCode
3 min read
design hash-map

Problem#

Design a data structure supporting add(number) and find(target)find returns true iff there exist two stored values whose sum equals target.

Examples#

  • add(1); add(3); add(5); find(4)true.
  • find(7)false.

Constraints#

  • Up to 10^4 adds and 10^4 finds; values fit in 32-bit int.

Approach#

Frequency map value → count. add increments. find iterates each key x, checks whether target - x exists; special-case when x == target - x and require count >= 2.

Solution#

TwoSum
class TwoSum {
unordered_map<int,int> cnt;
public:
void add(int number) { ++cnt[number]; }
bool find(int value) {
for (auto& [x, c] : cnt) {
int y = value - x;
if (x == y) { if (c >= 2) return true; }
else if (cnt.count(y)) return true;
}
return false;
}
};

Editorial#

Trading a sorted vector (faster find, slower add) for a hash map is the right call here because add calls dominate. The x == y guard catches the “use the same number twice” trap that’s easy to miss.

Complexity#

  • Time: O(1) add, O(n) find.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.