Skip to main content
Back to problems
#3843
Medium Algorithms

First element with unique frequency

Array Hash Table Counting
69.8% acceptance
Mar 15, 2026
74
6
You are given an integer array nums. Return the first element (left to right) whose frequency is unique. If none, return -1.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn first_unique_freq(nums: Vec<i32>) -> i32 {
    use std::collections::HashMap;

    let mut freq: HashMap<i32, i32> = HashMap::new();
    for &x in &nums {
      *freq.entry(x).or_insert(0) += 1;
    }

    let mut freq_count: HashMap<i32, i32> = HashMap::new();
    for &f in freq.values() {
      *freq_count.entry(f).or_insert(0) += 1;
    }

    for &x in &nums {
      let f = freq[&x];
      if freq_count[&f] == 1 {
        return x;
      }
    }

    -1
  }
}