LeetCode 172: Factorial Trailing Zeroes Solution

Master LeetCode problem 172 (Factorial Trailing Zeroes), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

172. Factorial Trailing Zeroes

Medium

Problem Explanation

Explanation

To count the number of trailing zeroes in the factorial of a number, we need to count the number of factors of 5 in the factorial. This is because the number of 5s in the prime factorization of a number will determine the number of trailing zeroes in its factorial. We can iteratively divide the number by 5 and sum up the quotients to get the total number of trailing zeroes.

Algorithm

  1. Initialize a variable count to 0.
  2. Iterate over the numbers from 5 to n in steps of 5.
  3. For each number, divide it by 5 and add the quotient to count.
  4. Return count as the number of trailing zeroes in n!.

Time Complexity

The time complexity of this algorithm is O(log n) since we are dividing the number by 5 in each iteration.

Space Complexity

The space complexity of this algorithm is O(1) as we are using only a constant amount of extra space.

Solution Code

class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        for (int i = 5; i <= n; i += 5) {
            int num = i;
            while (num % 5 == 0) {
                count++;
                num /= 5;
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 172 (Factorial Trailing Zeroes)?

This page provides optimized solutions for LeetCode problem 172 (Factorial Trailing Zeroes) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 172 (Factorial Trailing Zeroes)?

The time complexity for LeetCode 172 (Factorial Trailing Zeroes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 172 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 172 in Java, C++, or Python.

Back to LeetCode Solutions