LeetCode 1384: Total Sales Amount by Year Solution

Master LeetCode problem 1384 (Total Sales Amount by Year), 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.

1384. Total Sales Amount by Year

Problem Explanation

Explanation:

To solve this problem, we can iterate through the Product table and calculate the total sales amount per year for each product. We will use a HashMap to store the total sales amount for each year. Then, we can iterate through the HashMap to generate the desired result.

Algorithm:

  1. Create a HashMap to store the total sales amount per year.
  2. Iterate through the Product table.
  3. For each product, calculate the total sales amount and update the HashMap accordingly.
  4. Iterate through the HashMap to generate the result in the required format.

Time Complexity:

  • The time complexity for this approach is O(n), where n is the number of rows in the Product table.

Space Complexity:

  • The space complexity for this approach is O(n), where n is the number of unique years in the Product table.

: :

Solution Code

SELECT product_id,
       sum(CASE WHEN EXTRACT(YEAR FROM sale_date) = 2008 THEN sale_amount ELSE 0 END) AS `2008`,
       sum(CASE WHEN EXTRACT(YEAR FROM sale_date) = 2009 THEN sale_amount ELSE 0 END) AS `2009`,
       sum(CASE WHEN EXTRACT(YEAR FROM sale_date) = 2010 THEN sale_amount ELSE 0 END) AS `2010`
FROM Sales
GROUP BY product_id;

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1384 (Total Sales Amount by Year)?

This page provides optimized solutions for LeetCode problem 1384 (Total Sales Amount by Year) 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 1384 (Total Sales Amount by Year)?

The time complexity for LeetCode 1384 (Total Sales Amount by Year) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1384 on DevExCode?

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

Back to LeetCode Solutions