Skip to main content

Calculate Compressed Mean - Solution & Explanation

EasyPremiumFree on FleetCodeDatabase4 min readAsked at: Google
Practice this problem

Problem Statement

Table: Orders

+-------------------+------+
| Column Name       | Type |
+-------------------+------+
| order_id          | int  |
| item_count        | int  |
| order_occurrences | int  |
+-------------------+------+
order_id is column of unique values for this table.
This table contains order_id, item_count, and order_occurrences.

Write a solution to calculate the average number of items per order, rounded to 2 decimal places.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Orders table:
+----------+------------+-------------------+
| order_id | item_count | order_occurrences | 
+----------+------------+-------------------+
| 10       | 1          | 500               | 
| 11       | 2          | 1000              |     
| 12       | 3          | 800               |  
| 13       | 4          | 1000              | 
+----------+------------+-------------------+
Output
+-------------------------+
| average_items_per_order | 
+-------------------------+
| 2.70                    |
+-------------------------+
Explanation
The calculation is as follows:
 - Total items: (1 * 500) + (2 * 1000) + (3 * 800) + (4 * 1000) = 8900 
 - Total orders: 500 + 1000 + 800 + 1000 = 3300 
 - Therefore, the average items per order is 8900 / 3300 = 2.70

Approach Overview

Problem Overview: The table stores numbers in a compressed format where each value appears with a frequency count. Instead of listing every occurrence, the dataset stores num and how many times it appears. Your task is to compute the mean of the expanded dataset without actually expanding it.

Approach 1: Conceptual Expansion (Brute Force) (Time: O(n + total_frequency), Space: O(total_frequency))

A straightforward way to think about the problem is to expand the compressed representation into the full dataset. For every row, you would repeat num exactly frequency times, build the full list, then compute the average. The mean is simply sum(all numbers) / count(all numbers). While this works conceptually, it becomes extremely inefficient when frequencies are large because the expanded dataset can grow far beyond the original table size. SQL systems are not designed to materialize massive repeated rows just to compute an average.

This approach helps you understand the math behind the problem, but it should never be implemented directly in production queries. It wastes memory and increases computation time unnecessarily.

Approach 2: Aggregated Summation (Optimal) (Time: O(n), Space: O(1))

The key insight is that expanding the dataset is unnecessary. Each row contributes num × frequency to the total sum and frequency to the total count. Instead of repeating values, compute the weighted contribution directly using SQL aggregation.

You iterate through the table once and compute two aggregates:

SUM(num * frequency) gives the total sum of the expanded dataset, while SUM(frequency) gives the total number of elements. The compressed mean is simply:

SUM(num * frequency) / SUM(frequency)

This approach leverages database database aggregation functions and basic SQL arithmetic operations. Because the query only scans the table once and keeps constant intermediate state, the time complexity is O(n) and the space complexity is O(1). SQL engines are highly optimized for this type of aggregation, making it both concise and efficient.

You may also round the result to a specific number of decimal places depending on the problem requirements, often using ROUND() in MySQL. This keeps the output consistent with expected precision.

Recommended for interviews: Interviewers expect the aggregated summation approach. Recognizing that the compressed format represents a weighted dataset shows strong problem understanding. The brute force expansion demonstrates the intuition behind the formula, but the optimal SQL aggregation shows practical engineering judgment and knowledge of SQL aggregation patterns.

Solution

We use the SUM function to calculate the total quantity of products and the total number of orders, then divide the total quantity by the total number of orders to get the average. Finally, we use the ROUND function to round the result to two decimal places.

Code

MySQL

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Conceptual ExpansionO(n + total_frequency)O(total_frequency)Useful only for understanding how compressed data represents the full dataset
Aggregated Summation (SQL)O(n)O(1)Best approach for SQL queries; computes weighted mean directly using SUM()

Video Solution

Leetcode 2985 - Calculate Compressed Mean- Solved by Everyday Data Science | ROUND() SUM() AVG() • Everyday Data Science • 714 views views

Frequently Asked Questions

Is Calculate Compressed Mean easy or hard?
Calculate Compressed Mean is classified as an Easy database problem. The main challenge is recognizing that the table represents compressed data and that the mean can be computed using a weighted average formula instead of expanding the dataset.
Calculate Compressed Mean Python/Java solution
Interview platforms typically expect a SQL query for this problem because it is tagged as a database question. In application code like Python or Java, the same logic applies: iterate through the pairs, accumulate value * frequency and total frequency, then divide to compute the weighted average.
How to solve Calculate Compressed Mean in O(n)?
Scan the compressed table once and treat each row as a weighted value. Multiply the number by its frequency to compute its total contribution, then divide the total weighted sum by the total frequency. In SQL this becomes SUM(num * frequency) / SUM(frequency).
What is the best approach for Calculate Compressed Mean?
The best approach is aggregated summation using SQL. Compute SUM(num * frequency) for the total value contribution and divide it by SUM(frequency) for the total count. This avoids expanding the dataset and runs in O(n) time with O(1) extra space.
Is Calculate Compressed Mean asked at Google/Amazon/Meta?
This type of problem appears frequently in SQL and data analytics interviews at large tech companies. Variations of weighted averages and compressed datasets are common in companies that evaluate data querying and aggregation skills.
What data structure is used in Calculate Compressed Mean?
The problem relies on a relational database table that stores compressed numeric data using value–frequency pairs. The solution uses SQL aggregation functions such as SUM along with arithmetic operations to compute a weighted mean.
What is the time complexity of Calculate Compressed Mean?
The optimal SQL solution runs in O(n) time where n is the number of rows in the compressed table. The query performs a single pass to calculate SUM(num * frequency) and SUM(frequency). Space complexity is O(1) because only aggregate counters are stored.

Ready to solve this problem?

Practice Calculate Compressed Mean with our built-in code editor and test cases.

Practice on FleetCode