Turn an O(n²) search for a pair with a given sum into one O(n) pass
pair_sum_slow returns the indices (i, j), i < j, of two elements whose sum is target, or None, by checking every pair. Write pair_sum with the same contract in one pass.
Requirements:
- O(n) expected time; no sorting. If several pairs match, return any one of them.
- An element never pairs with itself:
pair_sum(&[3], 6)isNone, whilepair_sum(&[3, 3], 6)isSome((0, 1)). - The inputs are small enough that
target - xcannot overflow.
fn pair_sum_slow(nums: &[i32], target: i32) -> Option<(usize, usize)> {
for i in 0..nums.len() {
for j in i + 1..nums.len() {
if nums[i] + nums[j] == target {
return Some((i, j));
}
}
}
None
}
fn pair_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> {
// your code here
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Walk once with a HashMap from each seen value to its index. For x at i, look up target - x: a hit j gives (j, i), else insert x. Looking up before inserting stops x pairing with itself; O(n) average time, O(n) extra memory.
- Inserting
xbefore looking uptarget - x, so a single 3 pairs with itself for target 6 - Using a
HashSet, which tells whether a value was seen but keeps no index - Calling sort plus two pointers O(n): the sort alone is O(n log n) and loses the indices
- What is the worst-case time of this solution, and how does std's default hasher guard it?
- How would you find the first value that repeats, using only a
HashSet?
The nested loops check every pair because, for each x, they do not know whether the complement target - x has already been seen. A map from "value seen → its index" answers that question in O(1) on average, so one pass is enough.
use std::collections::HashMap;
fn pair_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> {
let mut seen: HashMap<i32, usize> = HashMap::new(); // value → index
for (i, &x) in nums.iter().enumerate() {
// look the complement up among the values seen so far, then remember x
if let Some(&j) = seen.get(&(target - x)) {
return Some((j, i));
}
seen.insert(x, i);
}
None
}
fn main() {
println!("{:?} {:?}", pair_sum(&[2, 7, 4, 5], 9), pair_sum(&[1, 2], 10)); // Some((0, 1)) None
println!("{:?} {:?}", pair_sum(&[3], 6), pair_sum(&[3, 3], 6)); // None Some((0, 1))
}The order "look up first, insert second" matters: insert x first, and for [3] with target 6 the lookup of 6 - 3 finds the element itself and returns (0, 0). The map holds only elements to the left of i, so j < i holds by construction. Time is O(n) on average: each HashMap operation costs O(1) on average, and the default SipHash hasher with a random key keeps an attacker from choosing inputs that pile every key into collisions. The price is O(n) extra memory. Sorting with two pointers needs no map, but costs O(n log n) and loses the original indices.