Python 0204.py
class Solution:
def countPrimes(self, n: int) -> int:
if n <= 2:
return 0
all = [True] * n
# scan only odd numbers
result = 1
for i in range(3, n, 2):
if all[i] == False:
continue
result += 1
# sieve
j = 3*i
while j < n:
all[j] = False
j += 2*i
return result
Difficulty
and has an acceptance rate of about 36% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Enumeration
- Math
- Number Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method countPrimes that returns the number of prime numbers strictly less than a given integer n. It employs a variant of the Sieve of Eratosthenes that deliberately ignores even numbers after handling the smallest prime (2). The algorithm initializes a boolean array, iterates over odd candidates, marks their odd multiples as non-prime, and accumulates a count of discovered primes.
Core Logic
Early Return for Small Input
The method begins by handling the situation where the input does not admit any prime numbers below it.
if n <= 2:
return 0
When n is 0, 1, or 2, the function immediately returns 0 because there are no prime numbers less than 2. This guard prevents unnecessary allocation of the boolean array for trivial cases.
Boolean Array Initialization
A list named all is created to represent the primality status of each integer from 0 up to n-1. All entries are initially set to True, indicating potential primality.
all = [True] * n
The array includes indices for even numbers, but the algorithm will never consult those entries after the initial setup, allowing the same structure to be reused without extra bookkeeping.
Counting the Prime 2
Since the sieve will only process odd numbers, the count of known primes is seeded with the prime number 2.
result = 1
This pre-increment ensures that the final result includes 2 without having to treat it as part of the main loop.
Iteration Over Odd Candidates
The main loop steps through odd integers starting at 3, up to but not including n. The step size of 2 guarantees that only odd indices are examined.
for i in range(3, n, 2):
if all[i] == False:
continue
result += 1
# sieve step follows
If the current odd index i has already been marked as non-prime (False), the loop skips further work for that value. Otherwise, i is a prime, and the counter result is incremented.
Sieve of Odd Multiples
For each discovered odd prime i, the algorithm marks its odd multiples as composite. The first multiple considered is 3*i, which is the smallest odd multiple greater than i itself. The increment 2*i preserves oddness, because adding an even multiple of an odd number yields another odd number.
j = 3 * i
while j < n:
all[j] = False
j += 2 * i
By starting at 3*i rather than i*i, the implementation avoids marking the prime itself and also skips even multiples that would already be known as non-prime. The inner loop continues until the multiple exceeds the bound n.
Final Result
After the outer loop finishes scanning all odd candidates, the accumulated result holds the total count of primes below n.
return result
Edge Cases Handled
The early return clause covers inputs where n is less than or equal to 2, ensuring the function returns a correct count of zero without proceeding to the sieve. The loop bounds (range(3, n, 2)) naturally handle the situation where n is just above 2, such as n = 3, by producing an empty iteration and leaving the result at the initial count of 1 (the prime 2). The inner while loop’s condition j < n guarantees that attempts to mark multiples never exceed the allocated array, preventing index errors for any valid n.
Performance Optimizations
The algorithm incorporates several deliberate choices to reduce work and memory traffic:
- Odd-only scanning: By iterating with a step of 2, the method eliminates half of the candidate numbers from consideration, effectively halving the number of loop iterations compared to a naïve full-range scan.
- Pre-counting the prime 2: Seeding the result with 1 removes the need to treat the even prime as a special case inside the main loop, simplifying the control flow.
- Skipping even multiples: The inner sieve starts at
3*iand increments by2*i, which means only odd multiples are visited. Even multiples are already known to be composite, so they are never written to the boolean array, reducing unnecessary assignments. - Early continuation: The
if all[i] == False: continueguard prevents the algorithm from performing the inner marking step for numbers that have already been identified as composite, avoiding redundant work.
These choices collectively lower the number of arithmetic operations and memory writes, yielding a faster execution profile for typical input sizes while maintaining a straightforward implementation.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered tiles on the floor, starting from zero and going all the way up to the number that was chosen. At the start, this code pretends that every single tile is a special number called a prime.
First, the code checks if the number is very small. If the number is zero, one, or two, it knows there are no primes to find, so it just stops immediately.
For bigger numbers, the process begins by assuming everything is a prime. Since the number two is the only even prime, the code starts by counting that one right away. Then, it walks down the line looking only at the odd numbered tiles. Every time it lands on a tile that is still marked as true, that means another prime has been discovered.
Once a prime is found, the code performs a clever trick to cross off any other numbers that can be built by multiplying that prime by something else, because those are not prime. It jumps along the line, flipping those tiles to false so they do not count anymore. It keeps skipping ahead like this until it reaches the very end of the row of tiles. By the time it finishes walking through the line, it knows exactly how many primes are hiding in that group.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | C# | Java | JS | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| qiyuangong | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| qiyuangong | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 263: Ugly Number
- problem 2427: Number of Common Factors
- problem 2761: Prime Pairs With Target Sum
- problem 3233: Find the Count of Numbers Which Are Not Special
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality