#762

Prime Number of Set Bits in Binary Representation

Easy
MathBit ManipulationBit ManipulationSet and Hash Map
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution precomputes the prime numbers and uses a bit manipulation technique to count set bits efficiently. This reduces the number of checks needed during the main loop, making it faster.

⚙️

Algorithm

7 steps
  1. 1Step 1: Precompute all prime numbers up to 20 (maximum possible set bits for numbers <= 10^6).
  2. 2Step 2: Create a set of these prime numbers for O(1) lookup.
  3. 3Step 3: Iterate through each number from left to right.
  4. 4Step 4: Count the number of set bits using bit manipulation.
  5. 5Step 5: Check if the count of set bits is in the set of prime numbers.
  6. 6Step 6: If it is, increment the count.
  7. 7Step 7: Return the final count.
solution.py13 lines
1# Full working Python code
2
3def count_prime_set_bits(left, right):
4    primes = {2, 3, 5, 7, 11, 13, 17, 19}
5    count = 0
6    for num in range(left, right + 1):
7        set_bits = bin(num).count('1')
8        if set_bits in primes:
9            count += 1
10    return count
11
12# Example usage
13print(count_prime_set_bits(6, 10))

Complexity note: The time complexity is O(n) since we iterate through the range once, and the space complexity is O(1) as we only store a fixed number of primes.

  • 1Understanding binary representation and set bits is crucial for this problem.
  • 2Precomputing primes allows for faster checks during the main loop.

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