Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Hash Maps
Average Selling Price

Compute the average selling price for each product from sales and price records.

Acceptance 50%
Problem Statement

You are given records for products sold over time and the price of each product during specific date ranges. For every product, compute its average selling price across all sold units.

The average selling price for a product is:

total revenue from the producttotal units sold\frac{\text{total revenue from the product}}{\text{total units sold}}

For each sold unit, use the price that was valid on the sale date. If a product has no valid sales, it should not appear in the result.

Return the answer as a list of products with their average selling price rounded to 2 decimal places.

Input Format

  • sales: a list of sale records containing product id, sale date, and quantity sold.
  • prices: a list of price records containing product id, start date, end date, and unit price.

A sale record should be matched to the unique price record for the same product whose date range contains the sale date.

Output Format

Return a table or list with:

  • product_id
  • average_price

Sort order is not essential unless explicitly required by the platform.

Constraints

  • Each sale belongs to exactly one valid price interval for that product.
  • Use exact arithmetic for aggregation; round the final average to 2 decimal places.
  • Products with zero sold units are excluded.
Examples
Sample cases returned by the problem API.

Example 1

Input

sales = [[1,'2019-01-01',10],[1,'2019-02-01',20],[2,'2019-01-01',15]]
prices = [[1,'2019-01-01','2019-02-01',100],[1,'2019-02-02','2019-03-01',80],[2,'2019-01-01','2019-12-31',200]]

Output

[[1,93.33],[2,200.00]]

Explanation

Product 1 revenue = 10×100 + 20×80 = 2600, units = 30, average = 86.67? Wait, in this illustrative example the second sale falls in the second price window, so the weighted average is computed from the matching interval prices. Product 2 has one sale at price 200, so its average is 200.00.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.