Start learning free

LESSON 239 OF 293 · SETS

Common Count in Rust: Counting Shared Values with HashSet

Practice Read the full explanation

Given two arrays of integers, a and b, return how many different values appear in both of them.

A value counts only once, however many times it appears in a or in b.

 

Example 1:

Input: a = [1, 2, 3, 4], b = [3, 4, 5]
Output: 2
Explanation: 3 and 4 are in both. 1 and 2 are only in a, and 5 is only in b.

Example 2:

Input: a = [7, 7, 8], b = [7, 9, 7]
Output: 1
Explanation: 7 is the only value in both. It appears twice in each, but it counts once.

Example 3:

Input: a = [1, 2], b = [3, 4]
Output: 0
Explanation: No value is in both.

 

Constraints:

  • a and b each have at least one number.
  • Every number is between -109 and 109.
STEP 1 OF 5
    Ctrl + Enter to check

    RUST · SETS

    Common Count in Rust, explained

    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

    1. Build set_a. a.into_iter().collect() turns the vector into an iterator of numbers, and collect() gathers them into a HashSet<i32>. Repeated values in a collapse into one entry. The type annotation on the variable is what tells collect() to build a set rather than a vector.
    2. Create an empty common set. It is declared with let mut because the loop will add to it.
    3. Loop over &b. Borrowing the vector gives each num as a reference to an i32.
    4. Test and insert. If set_a contains num, the value is in both vectors, so it goes into common. contains takes a reference, which is exactly what num is. insert takes the value itself, so the code writes *num to read the number behind the reference.
    5. 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() consumes a. The function owns its vectors, and a.into_iter() moves them into the iterator. Using a afterwards is a compile error: borrow of moved value: `a`. That is fine here because nothing needs a again, but if you did need it, a.iter() would borrow instead.
    • len() returns a usize. The function returns an i32, so as i32 converts it. Rust never converts between integer types on its own.
    • Two ways to write the last line. return common.len() as i32; and a bare common.len() as i32 with 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] and b = [7, 9, 7]. The set common is what keeps the answer at 1.
    • Comparing the sets' sizes. The size of set_a says nothing about overlap. Only values found in both count.
    • No overlap. When nothing is shared, common stays empty and the function returns 0.
    • Negative and large values. Any i32 works as a set element, so -5 and 1000000000 need no special handling.

    Testing

    • a = [1, 2, 3, 4], b = [3, 4, 5] gives 2.
    • a = [7, 7, 8], b = [7, 9, 7] gives 1.
    • a = [1, 2], b = [3, 4] gives 0.
    • a = [-5, 0, 1000000000], b = [1000000000, -5, -5, 0, 0] gives 3.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free