Skip to content
Problem 793 · LeetCode 793(opens in a new tab)

Preimage Size of Factorial Zeroes Function

HardBinary search

Write f(x) for the number of zeros at the end of x! (x factorial, the product 1 · 2 · … · x, where 0! = 1). For instance 7! = 5040, so f(7) = 1.

Given a whole number k, return how many non-negative whole numbers x have exactly k zeros at the end of x!, that is, f(x) = k.

Example 1

Input:  k = 2
Output: 5
Why:    x = 10, 11, 12, 13 and 14 all have 2 zeros
2 more examples and the constraints

Example 2

Input:  k = 11
Output: 0
Why:    f(49) = 10 and f(50) = 12; 11 is skipped

Example 3

Input:  k = 35
Output: 5
Why:    x = 145 to 149

Constraints

  • 0 ≤ k ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Binary search on xO(log² k)
  2. Check the jump digitsO(log k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for k = 1,000,000,000Verdict
Binary search on xO(log² k)
Fast and easy to trust
Check the jump digitsO(log k)
Best; no search at all

k = the number of trailing zeros asked for.

Edge cases to test

  • k = 0. x = 0, 1, 2, 3 and 4: the answer is 5. 0! is 1, which has no zeros.
  • The first gap. k = 5 is skipped, since 24! has 4 zeros and 25! has 6.
  • Two gaps in a row. k = 29 and k = 30 are both skipped, at x = 125.
  • Large k. k = 1,000,000,000 needs x near 4 billion, past a 32-bit int.
  • A gap near the top. k = 999,999,994 gives 0.

Common mistakes

  • Scanning x upward one at a time, which takes billions of steps.
  • Using 32-bit integers for x or the search bound 5k, which overflow.
  • Counting only x/5 and forgetting the extra 5s in 25, 125 and so on.

How to talk through it

  1. 1Clarify. Is 0 allowed as x? How large can k be?
  2. 2Count the zeros. Zeros come from factors of 5: x/5 + x/25 + …
  3. 3Use that f only grows. The matching x form one run, so binary search its two ends; note the answer is 0 or 5.
  4. 4Offer the digit test. Sizes 1, 6, 31, …; a digit of 5 means k is in a gap.
  5. 5Test out loud. Run k = 0, k = 5 and k = 30.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?