Problem overview
The function common_count receives two vectors of integers, a and b, and returns how many different values appear in both. A value counts once, however many times it shows up in either vector. With a = [1, 2, 3, 4] and b = [3, 4, 5] the shared values are 3 and 4, so the answer is 2. With a = [7, 7, 8] and b = [7, 9, 7] the only shared value is 7, which appears twice in each vector but counts once, so the answer is 1.
Approach: a set for fast lookups, a set for the answer
The direct way to compare two vectors is to take each value of b and scan all of a for it. That works, but it repeats a lot of searching. A HashSet answers "is this value in here?" in roughly constant time, so the plan is to load one vector into a set and then check the other vector against it.
The second idea handles duplicates. If the code only added 1 to a counter for every match, then b = [7, 9, 7] would count the 7 twice. A second set, common, fixes that: inserting a value that is already in a set changes nothing, so each shared value ends up in common exactly once. The answer is the size of that set.
Step by step
- Build
set_a.a.into_iter().collect()turns the vector into an iterator of numbers, andcollect()gathers them into aHashSet<i32>. Repeated values inacollapse into one entry. The type annotation on the variable is what tellscollect()to build a set rather than a vector. - Create an empty
commonset. It is declared withlet mutbecause the loop will add to it. - Loop over
&b. Borrowing the vector gives eachnumas a reference to ani32. - Test and insert. If
set_acontainsnum, the value is in both vectors, so it goes intocommon.containstakes a reference, which is exactly whatnumis.inserttakes the value itself, so the code writes*numto read the number behind the reference. - Return the size.
common.len()is the number of distinct shared values.
The solution in Rust
impl Solution {
fn common_count(a: Vec<i32>, b: Vec<i32>) -> i32 {
let set_a: HashSet<i32> = a.into_iter().collect();
let mut common: HashSet<i32> = HashSet::new();
for num in &b {
if set_a.contains(num) {
common.insert(*num);
}
}
return common.len() as i32;
}
}
A few Rust details matter here:
into_iter()consumesa. The function owns its vectors, anda.into_iter()moves them into the iterator. Usingaafterwards is a compile error:borrow of moved value: `a`. That is fine here because nothing needsaagain, but if you did need it,a.iter()would borrow instead.len()returns ausize. The function returns ani32, soas i32converts it. Rust never converts between integer types on its own.- Two ways to write the last line.
return common.len() as i32;and a barecommon.len() as i32with no semicolon mean the same thing at the end of a function.
Complexity
Time: O(m + n) on average, where m is the length of a and n the length of b. Building set_a visits each element of a once, and the loop visits each element of b once, with an average constant-time lookup and insert each time.
Space: O(m + n) in the worst case, for the two sets. common can never be larger than the smaller of the two inputs.
Edge cases and common mistakes
- Counting matches instead of distinct values. A counter that grows on every match returns 2 for
a = [7, 7, 8]andb = [7, 9, 7]. The setcommonis what keeps the answer at 1. - Comparing the sets' sizes. The size of
set_asays nothing about overlap. Only values found in both count. - No overlap. When nothing is shared,
commonstays empty and the function returns 0. - Negative and large values. Any
i32works as a set element, so -5 and 1000000000 need no special handling.
Testing
a = [1, 2, 3, 4],b = [3, 4, 5]gives2.a = [7, 7, 8],b = [7, 9, 7]gives1.a = [1, 2],b = [3, 4]gives0.a = [-5, 0, 1000000000],b = [1000000000, -5, -5, 0, 0]gives3.
