LeetCode 2117: Abbreviating the Product of a Range Solution

Master LeetCode problem 2117 (Abbreviating the Product of a Range), a hard 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.

2117. Abbreviating the Product of a Range

Hard

Problem Explanation

Explanation:

To solve this problem, we need to calculate the product of all integers in the inclusive range [left, right], abbreviate the product as described in the problem statement, and return the abbreviated form as a string.

Here is the algorithmic idea:

  1. Initialize a variable product to 1 to store the product of all integers in the range [left, right].
  2. Iterate from left to right, multiplying each integer with the product.
  3. Calculate the number of trailing zeros in the product and remove them.
  4. Count the remaining number of digits in the product.
  5. Abbreviate the product based on the number of digits and trailing zeros.

Time Complexity: O(n), where n is the number of integers in the range [left, right]. Space Complexity: O(1)

:

Solution Code

class Solution {
    public String abbreviate(int left, int right) {
        long product = 1;
        for (int i = left; i <= right; i++) {
            product *= i;
        }
        
        int zeros = 0;
        while (product % 10 == 0) {
            zeros++;
            product /= 10;
        }
        
        String productStr = Long.toString(product);
        int digits = productStr.length();
        
        if (digits > 10) {
            return productStr.substring(0, 5) + "..." + productStr.substring(digits - 5) + "e" + zeros;
        } else {
            return productStr + "e" + zeros;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2117 (Abbreviating the Product of a Range)?

This page provides optimized solutions for LeetCode problem 2117 (Abbreviating the Product of a Range) 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 2117 (Abbreviating the Product of a Range)?

The time complexity for LeetCode 2117 (Abbreviating the Product of a Range) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2117 on DevExCode?

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

Back to LeetCode Solutions