3591. Check if Any Element Has Prime Frequency
SourceWeekly Contest 455 Q1DifficultyEasyRating1234
Description
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.
Example 1:
Input: nums = [1,2,3,4,5,4]
Output: true
Explanation:
4 has a frequency of two, which is a prime number.
Example 2:
Input: nums = [1,2,3,4,5]
Output: false
Explanation:
All elements have a frequency of one.
Example 3:
Input: nums = [2,2,2,4,4]
Output: true
Explanation:
Both 2 and 4 have a prime frequency.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 100
Solutions
Solution 1: Counting + Prime Check
Thinking
We only need whether some value’s frequency is prime. Count first, then trial-divide each frequency.
A frequency is at most \(n\), so testing up to its square root is enough. Return true on the first prime frequency.
We use a hash table \(\text{cnt}\) to count the frequency of each element. Then, we iterate through the values in \(\text{cnt}\) and check if any of them is a prime number. If there is a prime, return true; otherwise, return false.
The time complexity is \(O(n \times \sqrt{M})\), and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\text{nums}\) and \(M\) is the maximum
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |