[LeetCode] First Element with Unique Frequency

3843. First Element with Unique Frequency

You are given an integer array nums.

Return an integer denoting the first element (scanning from left to right) in nums whose frequency is unique. That is, no other integer appears the same number of times in nums. If there is no such element, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int firstUniqueFreq(vector<int>& nums) {
unordered_map<int,int> f;
for(auto& n : nums) f[n]++;
unordered_map<int,vector<int>> gf;
for(auto& [k,v] : f) gf[v].push_back(k);
unordered_set<int> us;
for(auto& [k,v] : gf) if(v.size() == 1) us.insert(v[0]);
if(us.size() == 0) return -1;
for(int i = 0; i < nums.size(); i++) {
if(!us.count(nums[i])) continue;
return nums[i];
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/first-element-with-unique-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.