Python 0793.py
class Solution:
def preimageSizeFZF(self, k: int) -> int:
# at zero at the end means that some numbers of the factorial have prime factor 5,
# some have prime factor 2 (2*5=10). 2 is far more frequent, so only the 5s "complete" a 10.
# f(x) = k means that there is exactly k times a 5
# unfortunately a number may have several 5s as prime facators, e.g. 50 = 2 * 5 * 5
# the result will either be 5 or 0:
# if x is a multiple of 5 then f(x) = f(x+1) = f(x+2) = f(x+3) = f(x+4)
# however if x is more than once a multiple of 5 then k jumps by more than 1
# e.g. f(24) = 4 but f(25) = 6, there is no x such that f(x) = 5
# edge case
if k == 0:
return 5
# count trailing zeros of x
def tens(x):
result = 0
while x > 0:
x //= 5
result += x
return result
left = 0
right = 10 * k # rough estimate of upper bound
while left < right:
mid = (left + right) // 2
if tens(mid) < k:
left = mid + 1
else:
right = mid
# exact match => 5 numbers
# not exact => there's a jump and no f(x) = k
return 5 * (tens(left) == k)
Difficulty
and has an acceptance rate of about 45% (40k+ submissions).
Typical patterns to solve this problem:
- Binary Search
- 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 implementation solves the classic “preimage size of factorial trailing zeros” problem.
Given an integer k, it determines how many non-negative integers x satisfy the equation
f(x) = k, where f(x) counts the number of trailing zeros in x!.
Mathematically the answer is either 5 (a whole block of five consecutive numbers) or 0 (when k falls in a gap caused by a multiple of 25, 125, …).
The algorithm proceeds in three logical phases: handling the trivial zero case, computing the trailing-zero count for any candidate, and a binary search that locates the smallest x whose count meets or exceeds k. The final return value is derived from whether an exact match was found.
Edge-case handling
The only explicit edge case is k == 0.
For k = 0 the factorials of 0, 1, 2, 3, 4 all have zero trailing zeros, so the function immediately returns 5.
No other special-case logic is required because the binary search naturally deals with gaps in the sequence of possible k values (e.g., there is no x with f(x) = 5 because f(24) = 4 and f(25) = 6).
Core components
Zero-check
if k == 0:
return 5
This guard short-circuits the computation for the smallest input and returns the known block size.
Trailing-zero counter
def tens(x):
result = 0
while x > 0:
x //= 5
result += x
return result
The helper repeatedly divides x by 5, accumulating the quotient each time.
Each division accounts for one factor of 5 contributed by the numbers up to x; the sum therefore equals the total number of factor-5 pairs that form trailing zeros.
Using integer division (//) ensures the loop runs only as many times as there are powers of 5 less than or equal to x, which is very small even for large x.
Binary search for the lower bound
left = 0
right = 10 * k # rough upper bound
while left < right:
mid = (left + right) // 2
if tens(mid) < k:
left = mid + 1
else:
right = mid
The search maintains an invariant that left is the smallest candidate that could satisfy tens(x) >= k.
right is initialized to 10 * k, a simple over-estimate that guarantees the true answer lies within the interval.
At each iteration the midpoint is evaluated; if its zero count is below k, the lower half is discarded, otherwise the upper half is trimmed.
The loop terminates when left equals right, i.e., the first position where the count reaches or exceeds k.
Determining the final answer
return 5 * (tens(left) == k)
After the search, left holds the minimal x with tens(x) >= k.
If tens(left) equals k, a full block of five consecutive numbers shares that count, so the expression evaluates to 5.
If the count has jumped past k, the equality is false and the multiplication yields 0.
Performance considerations
The tens function runs in logarithmic time relative to its argument because each loop iteration reduces x by a factor of 5.
The binary search performs a logarithmic number of iterations with respect to the search interval, which itself is proportional to k.
Consequently the overall runtime grows roughly with the logarithm of k, making the solution efficient even for very large inputs.
Choosing 10 * k as the initial upper bound avoids the need for a more complex dynamic expansion while still guaranteeing coverage of the solution space.
All arithmetic uses plain integers, and the algorithm avoids any auxiliary data structures, keeping memory usage minimal.
ELI5 - Simplified Explanation
Imagine a big treasure chest filled with shiny golden marbles. Every time you multiply a bunch of numbers together, you get some zeroes at the end of the final result. A zero is special because it happens whenever a two and a five get together to play. Since there are always plenty of twos hiding in the numbers, the number of fives really tells the story of how many zeroes you will see.
Some numbers are extra special. If you have the number twenty-five, it is like having two fives hidden inside it, which makes the number of zeroes jump up quickly. Because of this jump, sometimes you might be looking for a certain number of zeroes, but that number just does not exist for any factorial.
The code starts by looking at the number k, which is the amount of zeroes you want to find. It uses a helpful little tool called tens that counts how many fives hide inside all the numbers up to a certain point. To find the answer, the code plays a game of guessing. It picks a number in the middle of a range and checks if it has enough zeroes. If the count is too small, it moves the left side of the range higher. If the count is big enough, it moves the right side of the range lower.
Once the guessing game finishes, it checks one last thing. If it found exactly the right amount of zeroes, it knows that five different numbers will have that same amount of zeroes because of how the math works. If it could not find that exact amount, it knows that the jump happened and no such number exists.
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Go | Python | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 172: Factorial Trailing Zeroes
Solved On The Same Day
- problem 1005: Maximize Sum Of Array After K Negations
- problem 935: Knight Dialer
- problem 1029: Two City Scheduling
- problem 1769: Minimum Number of Operations to Move All Balls to Each Box
- problem 2080: Range Frequency Queries
- problem 878: Nth Magical Number
- problem 902: Numbers At Most N Given Digit Set
- problem 1751: Maximum Number of Events That Can Be Attended II
- problem 1793: Maximum Score of a Good Subarray
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