Check if Any Element Has Prime Frequency - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,6,4,6,4]
Output: true
💡 Note: Element 4 appears 3 times and 3 is prime. Element 6 appears 2 times and 2 is prime. Since both frequencies are prime, return true.
Example 2 — No Prime Frequencies
$ Input: nums = [1,1,1,1]
Output: false
💡 Note: Element 1 appears 4 times. 4 is not prime (divisible by 1, 2, and 4), so return false.
Example 3 — Single Element
$ Input: nums = [5]
Output: false
💡 Note: Element 5 appears 1 time. 1 is not prime (prime numbers must be greater than 1), so return false.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Prime Frequency Checker INPUT nums = [4, 6, 4, 6, 4] 4 6 4 6 4 [0] [1] [2] [3] [4] Array of 5 integers Blue = element 4 Green = element 6 Task: Check if any element has a prime frequency ALGORITHM (Hash) 1 Build Frequency Map Count occurrences using hash freq[4] = 3 freq[6] = 2 (HashMap) 2 Get All Frequencies Extract: [3, 2] 3 Check Each for Prime isPrime(3)? isPrime(2)? 3: divisors = 1, 3 PRIME 2: divisors = 1, 2 PRIME 4 Return Result Found prime freq --> true FINAL RESULT Frequency Analysis: 4 appears 3 times 3 is PRIME 6 appears 2 times 2 is PRIME Output: true Both frequencies are prime! At least one prime found: OK Key Insight: Use a HashMap to count element frequencies in O(n) time. Then check each frequency value against the prime check function. A number n is prime if it has exactly 2 divisors: 1 and n. Time: O(n * sqrt(maxFreq)) | Space: O(k) where k = unique elements TutorialsPoint - Check if Any Element Has Prime Frequency | Hash Approach
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~12 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen