Abbreviating the Product of a Range - Problem

You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right].

Since the product may be very large, you will abbreviate it following these steps:

  1. Count all trailing zeros in the product and remove them. Let us denote this count as C.
  2. Denote the remaining number of digits in the product as d. If d > 10, then express the product as <pre>...<suf> where <pre> denotes the first 5 digits of the product, and <suf> denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged.
  3. Finally, represent the product as a string "<pre>...<suf>eC".

Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].

Input & Output

Example 1 — Small Range
$ Input: left = 1, right = 4
Output: 24e0
💡 Note: Product is 1×2×3×4 = 24. No trailing zeros. Since 24 has 2 digits (≤ 10), return "24e0".
Example 2 — With Trailing Zeros
$ Input: left = 2, right = 5
Output: 12e1
💡 Note: Product is 2×3×4×5 = 120. Remove 1 trailing zero → 12. Since 12 has 2 digits (≤ 10), return "12e1".
Example 3 — Large Range
$ Input: left = 1, right = 18
Output: 64023...05728e3
💡 Note: Product is 18! = 6402373705728000. Remove 3 trailing zeros → 6402373705728. Since this has 13 digits (>10), return first 5 digits + '...' + last 5 digits + 'e3'.

Constraints

  • 1 ≤ left ≤ right ≤ 104
  • The product can be extremely large

Visualization

Tap to expand
Abbreviating the Product of a Range INPUT Range [left, right] 1 2 3 4 Product = 1 x 2 x 3 x 4 Input Values left = 1 right = 4 Product = 24 ALGORITHM STEPS 1 Calculate Product Use log to track digits sum(log10(i)) for i in range 2 Count Trailing Zeros C = min(count_2, count_5) 24 has 0 trailing zeros 3 Check Digit Count d = 2 digits (d <= 10) Keep number unchanged 4 Format Output Append "eC" suffix "24" + "e" + "0" = "24e0" Logarithmic Approach log10(1x2x3x4) = sum of logs = 0 + 0.301 + 0.477 + 0.602 FINAL RESULT Abbreviated Product Breakdown Product: 24 Trailing zeros (C): 0 Digits (d): 2 (d <= 10) Output: "24e0" OK - Verified! 1 x 2 x 3 x 4 = 24 No abbreviation needed Key Insight: Use logarithms to handle large products without overflow. The sum of log10(i) gives the number of digits. Track factors of 2 and 5 separately to count trailing zeros. For d > 10, extract first 5 and last 5 digits. Time: O(right - left) | Space: O(1) for tracking prefix/suffix digits TutorialsPoint - Abbreviating the Product of a Range | Logarithmic Approach
Asked in
Google 45 Microsoft 38
29.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen