#170
Easy Algorithms Two sum iii data structure design
Array Hash Table Two Pointers Design Data Stream
39.1% acceptance
Apr 1, 2026
711
462
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, it returns false.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::HashMap;
struct TwoSum {
map: HashMap<i32, i32>,
}
impl TwoSum {
fn new() -> Self {
TwoSum { map: HashMap::new() }
}
fn add(&mut self, number: i32) {
*self.map.entry(number).or_insert(0) += 1;
}
fn find(&self, value: i32) -> bool {
for (&num, &count) in &self.map {
let complement = value - num;
if complement == num {
if count > 1 {
return true;
}
} else if self.map.contains_key(&complement) {
return true;
}
}
false
}
}