#2117

Abbreviating the Product of a Range

Hard
MathNumber TheoryMathematical PropertiesLogarithmic Functions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

This approach leverages mathematical properties to avoid computing the full product directly. By using logarithms and modular arithmetic, we can efficiently find the required digits and trailing zeros.

⚙️

Algorithm

5 steps
  1. 1Step 1: Count the number of trailing zeros by finding the minimum of the counts of factors 2 and 5 in the range.
  2. 2Step 2: Use logarithms to calculate the sum of logarithms of numbers in the range to find the total number of digits.
  3. 3Step 3: Calculate the last 5 digits using modular arithmetic.
  4. 4Step 4: Calculate the first 5 digits using exponentiation and logarithms.
  5. 5Step 5: Format the result based on the number of digits and trailing zeros.
solution.py41 lines
1# Full working Python code
2import math
3
4def abbreviate_product(left, right):
5    trailing_zeros = 0
6    count_2 = count_5 = 0
7    for i in range(left, right + 1):
8        while i % 2 == 0:
9            count_2 += 1
10            i //= 2
11        while i % 5 == 0:
12            count_5 += 1
13            i //= 5
14    trailing_zeros = min(count_2, count_5)
15
16    # Calculate the last 5 digits
17    last_digits = 1
18    for i in range(left, right + 1):
19        last_digits = (last_digits * (i % 100000)) % 100000
20
21    # Calculate the total number of digits
22    total_log = sum(math.log10(i) for i in range(left, right + 1))
23    total_digits = int(total_log) + 1
24
25    # Calculate first 5 digits
26    first_digits = 1
27    for i in range(left, right + 1):
28        first_digits *= i
29        while first_digits >= 100000:
30            first_digits //= 10
31
32    first_digits_str = str(first_digits)[:5]
33    last_digits_str = str(last_digits).rstrip('0')[-5:]
34
35    if total_digits > 10:
36        result = f'{first_digits_str}...{last_digits_str}e{trailing_zeros}'
37    else:
38        result = f'{first_digits_str}e{trailing_zeros}'
39    return result
40
41print(abbreviate_product(1, 4))

Complexity note: The time complexity is O(n) because we iterate through the range only a few times to calculate the necessary values without storing large products.

  • 1Understanding trailing zeros is key to simplifying large products.
  • 2Logarithmic properties help manage large numbers effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.