DSA interview question
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).
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
Input (L, R) | Output | Explanation |
|---|---|---|
(1, 10) | 4 | 2, 3, 5, 7 |
(10, 20) | 4 | 11, 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⁷.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in