1251. Average Selling Price LeetCode Solution
In this guide, you will get 1251. Average Selling Price LeetCode Solution with the best time and space complexity. The solution to Average Selling Price problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Average Selling Price solution in C++
- Average Selling Price solution in Java
- Average Selling Price solution in Python
- Additional Resources

Problem Statement of Average Selling Price
Table: Prices
+—————+———+
| Column Name | Type |
+—————+———+
| product_id | int |
| start_date | date |
| end_date | date |
| price | int |
+—————+———+
(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the price of the product_id in the period from start_date to end_date.
For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.
Table: UnitsSold
+—————+———+
| Column Name | Type |
+—————+———+
| product_id | int |
| purchase_date | date |
| units | int |
+—————+———+
This table may contain duplicate rows.
Each row of this table indicates the date, units, and product_id of each product sold.
Write a solution to find the average selling price for each product. average_price should be rounded to 2 decimal places. If a product does not have any sold units, its average selling price is assumed to be 0.
Return the result table in any order.
The result format is in the following example.
Example not found
Constraints not found
Complexity Analysis
- Time Complexity: Google AdSense
- Space Complexity: Google Analytics
1251. Average Selling Price LeetCode Solution in C++
SELECT
Prices.product_id,
IFNULL(
ROUND(
SUM(Prices.price * UnitsSold.units) / SUM(UnitsSold.units),
),
) AS average_price
FROM Prices
LEFT JOIN UnitsSold
ON (
Prices.product_id = UnitsSold.product_id
AND UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date)
GROUP BY 1;
/* code provided by PROGIEZ */
1251. Average Selling Price LeetCode Solution in Java
N/A
// code provided by PROGIEZ
1251. Average Selling Price LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.