#793

Preimage Size of Factorial Zeroes Function

Hard
MathBinary SearchBinary SearchMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(n))
Space
O(1)
O(1)
💡

Intuition

Time O(log(n))Space O(1)

Instead of calculating trailing zeros for every number, we can use binary search to find the range of numbers whose factorials have exactly k trailing zeros. This drastically reduces the number of calculations needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Define a function to calculate the number of trailing zeros in x! as before.
  2. 2Step 2: Use binary search to find the smallest x such that f(x) >= k.
  3. 3Step 3: Use binary search again to find the smallest x such that f(x) > k.
  4. 4Step 4: The difference between the two x values gives the count of integers x such that f(x) = k.
solution.py24 lines
1# Full working Python code
2
3def trailing_zeros(n):
4    count = 0
5    while n > 0:
6        n //= 5
7        count += n
8    return count
9
10def preimage_size_fzf(k):
11    def binary_search(target):
12        left, right = 0, 5 * (target + 1)
13        while left < right:
14            mid = (left + right) // 2
15            if trailing_zeros(mid) < target:
16                left = mid + 1
17            else:
18                right = mid
19        return left
20
21    left = binary_search(k)
22    right = binary_search(k + 1)
23    return right - left
24

Complexity note: The time complexity is O(log(n)) due to the binary search, which significantly reduces the number of checks needed compared to the brute force method.

  • 1The number of trailing zeros in a factorial is determined by the number of times 5 is a factor in the numbers leading up to that factorial.
  • 2Using binary search allows us to efficiently find the range of integers that meet the criteria, rather than checking each integer one by one.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.