Factorial Trailing Zeroes

Medium

Topics
Math

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

Example 1

11!22!63!
The answer counts the zeros at the end of 3!, not the zeros anywhere in it. Those factorials grow far past any integer type, so the number itself is never computed — for 3! the answer is 0.
Cells are the first few factorials; shaded ones already end in a zero.
Input:  n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2

11!22!63!244!1205!
ends in a zero
Input:  n = 5
Output: 1
Explanation: 5! = 120.

Example 3

empty array
Input:  n = 0
Output: 0

Constraints

  • 0 <= n <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

A trailing zero comes from a factor of 10, and 10 is 2 times 5. In any factorial there are far more factors of 2 than of 5 — every second number contributes a 2, only every fifth a 5 — so the number of 5s is the binding constraint and the answer is simply how many times 5 divides n!.

Counting those is not n / 5, because 25 contributes two 5s, 125 three, and so on. The total is

n/5 + n/25 + n/125 + ...   (integer division, until the term is 0)

which the loop computes by repeatedly dividing n by 5 and accumulating. Each division counts the multiples of the next power of 5, so a number like 25 is counted once as a multiple of 5 and again as a multiple of 25 — exactly its two factors.

Approach

  1. While n > 0: divide n by 5 and add the result to the count.

Dry Run

n = 100

n = 100 // 5  = 20   count 20
n = 20  // 5  = 4    count 24
n = 4   // 5  = 0    count 24, loop ends

answer 24

check: multiples of 5 up to 100 -> 20 of them
       of those, multiples of 25 -> 4 extra
       total 24  ✓

n = 3  ->  3 // 5 = 0, count 0   (3! = 6, no trailing zero)

Complexity

  • Time — O(log n) base 5, so a handful of iterations even for huge n.
  • Space — O(1).

Common Pitfalls

  • Computing n! and counting zeros. It overflows immediately and is the thing the problem is designed to rule out.
  • Returning n / 5 only, which undercounts every multiple of 25.
  • Counting factors of 2 as well and taking the minimum. Correct but redundant: 2s always outnumber 5s.
  • Adding n / 5^k with a recomputed power each time, which risks overflow in the power for large k. Dividing n in place avoids it.

Full Solution — all languages

class Solution:
    def trailingZeroes(self, n):
        count = 0
        while n > 0:
            n //= 5
            count += n
        return count
SensAI
Beta
Tap the mic to stop voice mode