PPractick

DSA interview question

Count Primes in a Range [L, R] (Sieve + Prefix Counts)

Hard · Algorithms · Topics: math, number theory, sieve

The problem

A math-quiz backend gets thousands of questions like "how many primes are there between L and R?", with R up to 10⁶. Testing each number for primality per query repeats the same work over and over. Instead, run the Sieve of Eratosthenes once up to the maximum R, build a prefix count cnt[x] = number of primes ≤ x, and answer every query in O(1) as cnt[R] − cnt[L − 1].

Example: L = 10, R = 20 → 4 (11, 13, 17, 19).

Function signature

vector<int> buildPrimeCounts(int maxN);       // cnt[x] = number of primes <= x
int countPrimes(const vector<int>& cnt, int l, int r);  // 1 <= l <= r <= maxN

Test cases

Input (L, R)OutputExplanation
(1, 10)42, 3, 5, 7
(10, 20)411, 13, 17, 19
(2, 2)1
(14, 16)0
(1, 1000000)78498π(10⁶)

(Confirm: 1 is not prime; many queries share the same maximum R, up to about 10⁶–10⁷.)

How interviewers phrase it

Clarifying questions to ask

  1. How large can R be? (About 10⁶–10⁷ fits a sieve; 10¹² needs a segmented sieve.)
  2. How many queries are there?
  3. Is the range inclusive at both ends?

Follow-ups to expect

  1. "How does the sieve work?"
  2. "Why start crossing out at p²?"
  3. "Why prefix counts?"
  4. "What if R is 10¹² but R − L ≤ 10⁶?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in