Python 0172.py
class Solution:
def trailingZeroes(self, n: int) -> int:
# count factors which are multiple of 5
# (there are many more multiples of 2, no need to count them)
result = 0
for i in range(5, n+1, 5):
n = i
while n % 5 == 0:
result += 1
n //= 5
return result
Difficulty
and has an acceptance rate of about 47% (1+ million submissions).
Typical patterns to solve this problem:
- Math
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 trailingZeroes that computes the number of trailing zeroes in the factorial of a non-negative integer n. The algorithm focuses on counting the factors of 5 that appear in the product sequence from 1 to n, because each pair of a factor 2 and a factor 5 contributes a trailing zero, and factors of 2 are abundant relative to factors of 5.
Core Logic
The method begins by initializing an accumulator result to zero. This variable will hold the total count of factor 5 occurrences.
result = 0
A for loop iterates over every multiple of 5 up to and including n. The loop step size of 5 ensures that only numbers that can contribute at least one factor of 5 are examined, eliminating unnecessary checks on numbers that are not divisible by 5.
for i in range(5, n + 1, 5):
Inside the loop, the current multiple i is assigned back to the variable n. This temporary reassignment allows the inner while loop to repeatedly divide the current number by 5, extracting all powers of 5 present in that specific multiple.
n = i
The while loop continues as long as the temporary n remains divisible by 5. Each successful division indicates another factor of 5, so the accumulator result is incremented, and n is reduced by integer division with 5. This process captures numbers such as 25 (which contributes two factors of 5) and 125 (which contributes three factors of 5) in a single iteration.
while n % 5 == 0:
result += 1
n //= 5
After the loop finishes processing all multiples of 5, the method returns the accumulated count, which equals the number of trailing zeroes in n!.
return result
Edge Cases
When n is less than 5, the range in the for loop produces no iterations, leaving result at its initial value of zero. This correctly reflects that factorials of numbers 0 through 4 have no trailing zeroes.
For values of n that are exact powers of 5, such as 5, 25, 125, etc., the inner while loop extracts multiple factors from a single iteration, ensuring that higher powers of 5 are fully accounted for without requiring separate passes.
When n is a very large integer, the loop still processes only the multiples of 5, and the inner division reduces each examined number quickly, preventing excessive work on numbers that contain many factors of 5.
Performance Considerations
The algorithm reduces the number of iterations by stepping through the range with an increment of 5, thereby skipping all numbers that cannot contribute a factor of 5. This selective iteration cuts down the total loop count roughly to one fifth of the naïve approach that would examine every integer up to n.
Within each iteration, the inner while loop divides the current multiple by 5 until it is no longer divisible. Because each division reduces the value exponentially, the number of inner loop executions for any given multiple is bounded by the logarithm of that multiple base 5. Consequently, the overall work performed scales with the total number of factor 5 occurrences rather than with the magnitude of n itself.
The reuse of the variable n as a temporary holder for each multiple avoids the allocation of additional storage, keeping the memory footprint minimal throughout execution. The method relies solely on integer arithmetic, which is efficient on typical hardware.
ELI5 - Simplified Explanation
Imagine you have a giant pile of blocks, and you want to know how many zeros are hiding at the end of a big number. To find these zeros, you look for pairs of two and five because when those two numbers hug each other, they create a ten, and tens always end in a zero. Since there are always plenty of twos in the world, the goal is just to count how many times the number five can hide inside the numbers up to your big number.
The code starts with a count of zero. Then, it goes through every number that can be divided by five. For each of those numbers, it checks to see how many fives are tucked away inside. If a number is twenty-five, it actually has two fives hidden inside, so the code counts both of them. It keeps doing this for every multiple of five until it finishes checking all the numbers. Every time it finds a five, it adds one to the final count.
Code Quality
Complexity Analysis
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 | Java | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | AdelDaniel | Dart | |||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| gaosq0604 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| AdelDaniel | Dart | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| gaosq0604 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 233: Number of Digit One
- problem 793: Preimage Size of Factorial Zeroes Function
- problem 2117: Abbreviating the Product of a Range
- problem 2245: Maximum Trailing Zeros in a Cornered Path
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 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- 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