Check if Any Element Has Prime Frequency Problem
#3591
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3591.
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
Solution
Approach: Count, Then Test Primality
Count how often each value occurs with a hash map, then test every count for primality by trial division up to its square root. Return true as soon as one count is prime.
Complexity: O(n * sqrt(n)) time in the worst case and O(n) space.
from math import sqrt
class Solution:
def checkPrimeFrequency(self, nums: List[int]) -> bool:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
cnt = Counter(nums)
return any(is_prime(x) for x in cnt.values())