#3591

Check if Any Element Has Prime Frequency

Easy
ArrayHash TableMathCountingNumber TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a hash map to count frequencies efficiently, then check for primes in a single pass. This reduces unnecessary computations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each element using a hash map.
  2. 2Step 2: Check if any frequency is prime using a helper function.
  3. 3Step 3: Return true if any frequency is prime, otherwise return false.
solution.py13 lines
1def is_prime(n):
2    if n <= 1:
3        return False
4    for i in range(2, int(n**0.5) + 1):
5        if n % i == 0:
6            return False
7    return True
8
9def prime_frequency(nums):
10    freq = {}
11    for num in nums:
12        freq[num] = freq.get(num, 0) + 1
13    return any(is_prime(count) for count in freq.values())

Complexity note: Counting frequencies is O(n) and checking primes for each frequency is efficient due to direct access in the hash map.

  • 1Prime numbers are only greater than 1 and have no divisors other than 1 and themselves.
  • 2Using a hash map allows for efficient frequency counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.