#677
Medium Algorithms Map sum pairs
Hash Table String Design Trie
57.1% acceptance
Feb 20, 2026
1732
166
MapSum: insert key-value pairs, sum returns total value of keys with the
given prefix.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::HashMap;
struct MapSum {
map: HashMap<String, i32>,
}
impl MapSum {
fn new() -> Self {
MapSum { map: HashMap::new() }
}
fn insert(&mut self, key: String, val: i32) {
self.map.insert(key, val);
}
fn sum(&self, prefix: String) -> i32 {
self.map.iter()
.filter(|(k, _)| k.starts_with(&prefix))
.map(|(_, &v)| v)
.sum()
}
}