Factorial Trailing Zeroes LeetCode Solution

Last updated on February 2nd, 2025 at 06:47 am

Here, we see Factorial Trailing Zeroes LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Math

Companies

Bloomberg

Level of Question

Medium

Factorial Trailing Zeroes LeetCode Solution

Factorial Trailing Zeroes LeetCode Solution

1. Problem Statement

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

Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.

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 = 0
Output: 0

2. Coding Pattern Used in Solution

This pattern involves solving a problem using mathematical properties and iterative calculations. The code leverages the mathematical insight that the number of trailing zeroes in n! is determined by the number of factors of 5 in the numbers from 1 to n.

3. Code Implementation in Different Languages

3.1 Factorial Trailing Zeroes C++

class Solution {
public:
    int trailingZeroes(int n) {
        int count = 0;
        for (long long i = 5; n / i; i *= 5)
            count += n / i;
        return count;        
    }
};

3.2 Factorial Trailing Zeroes Java

class Solution {
    public int trailingZeroes(int n) {
        int r = 0;
        while (n > 0) {
            n /= 5;
            r += n;
        }
        return r;        
    }
}

3.3 Factorial Trailing Zeroes JavaScript

var trailingZeroes = function(n) {
    let numZeroes = 0;
    for (let i = 5; i <= n; i *= 5) {
        numZeroes += Math.floor(n / i);
    }
    return numZeroes;    
};

3.4 Factorial Trailing Zeroes Python

class Solution(object):
    def trailingZeroes(self, n):
        if(n < 0):
            return -1
        output = 0
        while(n >= 5):
            n //= 5
            output += n
        return output 

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(log₅(n))O(1)
JavaO(log₅(n))O(1)
JavaScriptO(log₅(n))O(1)
PythonO(log₅(n))O(1)
  • The code is efficient and leverages a mathematical property to solve the problem in logarithmic time.
  • It uses a Mathematical Iterative Pattern to count the number of factors of 5 in n!.
  • The time complexity is O(log₅(n)), and the space complexity is O(1) across all implementations.
Scroll to Top