Advertisement

Factorial Trailing Zeroes - LeetCode 172 Solution

Factorial Trailing Zeroes - Complete Solution Guide

Factorial Trailing Zeroes is LeetCode problem 172, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

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 Constraints: 0 <= n <= 10 4 Follow up: Could you write a solution that works in logarithmic time complexity?

Detailed Explanation

The problem asks us to find the number of trailing zeroes in the factorial of a given non-negative integer 'n'. A trailing zero is a zero digit at the end of a number's decimal representation. For example, 5! = 120 has one trailing zero, and 10! has two trailing zeroes. The input is a non-negative integer 'n' (0 <= n <= 10^4), and the output is the number of trailing zeroes in n!.

Solution Approach

The solution counts the number of factors of 5 in the prime factorization of n!. This is done by iteratively dividing 'n' by 5 and adding the quotient to the count. In each iteration, we are essentially counting the multiples of 5, 25, 125, and so on, that are less than or equal to 'n'. The sum of these counts gives us the total number of factors of 5, which is equal to the number of trailing zeroes.

Step-by-Step Algorithm

  1. Step 1: Initialize a variable 'count' to 0. This variable will store the number of trailing zeroes.
  2. Step 2: While 'n' is greater than 0, perform the following steps:
  3. Step 3: Divide 'n' by 5 using integer division (n = n // 5 in Python or n /= 5 in other languages). This gives the number of multiples of 5 in the range [1, n].
  4. Step 4: Add the result of the division to the 'count'.
  5. Step 5: Repeat steps 3 and 4 until 'n' becomes 0.
  6. Step 6: Return the 'count'.

Key Insights

  • Insight 1: Trailing zeroes in a factorial are produced by pairs of 2 and 5 in the prime factorization of the factorial. Since there are always more factors of 2 than factors of 5, the number of trailing zeroes is determined by the number of factors of 5.
  • Insight 2: To find the number of factors of 5 in n!, we need to count how many multiples of 5, 25, 125, etc., are present in the numbers from 1 to n. A number like 25 contributes two factors of 5 (5*5), 125 contributes three factors of 5 (5*5*5), and so on.
  • Insight 3: We can efficiently count the factors of 5 by repeatedly dividing 'n' by increasing powers of 5 (5, 25, 125, ...). We keep track of the sum of the integer quotients obtained at each division.

Complexity Analysis

Time Complexity: O(log(n))

Space Complexity: O(1)

Topics

This problem involves: Math.

Companies

Asked at: Google.