Start learning free

LESSON 237 OF 293 · SETS

Unique Count in Rust: Counting Distinct Values with a HashSet

Practice Read the full explanation

Given an array of integers nums, return how many different values it has.

A value that appears several times counts only once.

 

Example 1:

Input: nums = [4, 7, 4, 1, 7]
Output: 3
Explanation: The different values are 4, 7 and 1. The second 4 and the second 7 are repeats, so they don't count again.

Example 2:

Input: nums = [5, 5, 5]
Output: 1
Explanation: Every number is 5, so there is only one different value.

Example 3:

Input: nums = [-2, 0, 3, 8]
Output: 4
Explanation: No value repeats, so every number counts.

 

Constraints:

  • nums has at least one number.
  • Every number is between -109 and 109.
STEP 1 OF 2
    Ctrl + Enter to check

    RUST · SETS

    Unique Count in Rust, explained

    Problem overview

    The function unique_count receives a vector of integers, nums, and returns how many different values it holds. A value that appears several times counts once. For [4, 7, 4, 1, 7] the answer is 3, because the different values are 4, 7 and 1. For [5, 5, 5] it is 1, and for [-2, 0, 3, 8] it is 4.

    Approach: let a set remove the repeats

    A set holds each value at most once. Adding a value that is already inside changes nothing, and checking whether a value is inside is fast. So if you put all the numbers into a set, the repeats disappear by themselves, and the set's size is the number of different values.

    The alternative is sorting the vector and counting the places where the value changes, which costs O(n log n). The set needs a single pass.

    Step by step

    1. Build the set. nums.into_iter().collect() takes the numbers one by one and gathers them into the type written on the variable, HashSet<i32>. The lesson already imports HashSet.
    2. Return its size. unique.len() is a usize, so as i32 converts it to the function's return type.

    The solution in Rust

    impl Solution {
        fn unique_count(nums: Vec<i32>) -> i32 {
            let unique: HashSet<i32> = nums.into_iter().collect();
            return unique.len() as i32;
        }
    }
    

    The Rust details worth a closer look:

    • collect() picks its target from the type. The same iterator could be collected into a Vec, a HashMap or a HashSet. The annotation HashSet<i32> on unique tells it which one to build. Without an annotation, the compiler can't tell and reports an error.
    • into_iter() consumes the vector. It yields the i32 values themselves, which is what the HashSet<i32> needs. nums.iter() would yield &i32 references and would collect into a HashSet<&i32> instead. After into_iter(), nums can't be used.
    • as i32. len() returns usize, and Rust doesn't convert between integer types on its own. The as cast truncates silently if the value doesn't fit, but a vector of that size would need billions of elements, so the cast is safe here.
    • No order. A HashSet doesn't remember the order of its values, which doesn't matter for counting.

    Complexity

    Time: O(n) on average. Each of the n numbers is inserted once, and an insertion takes constant time on average.

    Space: O(k), where k is the number of different values. In the worst case, when nothing repeats, k equals n.

    Tracing the example

    With [4, 7, 4, 1, 7], the set receives 4, then 7, then 4 again, which changes nothing, then 1, then 7 again, which also changes nothing. It ends with three values, so len() is 3. The same call on [5, 5, 5] leaves a set with one value.

    A loop with insert would do the same job, one value at a time. collect() is the idiomatic shortcut: it creates the set and inserts every value for you.

    Edge cases and common mistakes

    • Returning nums.len(). That counts every element, repeats included. For [4, 7, 4, 1, 7] it gives 5.
    • Negative numbers and zero. They are values like any other: [-2, 0, 3, 8] has 4.
    • All equal. [5, 5, 5] collapses to one element.
    • Forgetting the cast. Returning unique.len() directly doesn't compile, because usize isn't i32.

    Testing

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