[LeetCode] Check if Any Element Has Prime Frequency

3591. Check if Any Element Has Prime Frequency

You are given an integer array nums.

Return true if the frequency of any element of the array is prime, otherwise, return false.

The frequency of an element x is the number of times it occurs in the array.

A prime number is a natural number greater than 1 with only two factors, 1 and itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
bool prime(int n) {
if(n == 1) return false;
for(int i = 2; i * i <= n; i++) {
if(n % i == 0) return false;
}
return true;
}
public:
bool checkPrimeFrequency(vector<int>& nums) {
unordered_map<int,int> freq;
for(auto& n : nums) freq[n]++;
for(auto& [_,cnt] : freq) {
if(prime(cnt)) return 1;
}
return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/23/PS/LeetCode/check-if-any-element-has-prime-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.