Factorial Trailing Zeroes

MEDIUM

Given an integer n, return the number of trailing zeroes in n! (n factorial).

Follow up: Could you write a solution that works in logarithmic time complexity?

Examples:

Example 1:

Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Example 3:

Input: n = 10
Output: 2
Explanation: 10! = 3628800, two trailing zeros. (From 5 and 10)

Example 4:

Input: n = 0
Output: 0
Explanation: 0! = 1, no trailing zero.

Constraints:

  • 0 <= n <= 104 (For the brute-force approach, calculating n! might overflow for larger n, but the optimal solution handles this).

Function Signature (Python):

class Solution:
    def trailingZeroes(self, n: int) -> int:
        # Your code here
        pass

 

Nerchuko Academy · Free DS Interview Prep