15% off all plans & roadmaps Use code
See plansEditorial
Core insight
Calculate Compressed Mean · Sliding Window
Core Insight for Calculate Compressed Mean
The mean is sum / count, and both are available after a single pass: the count is just the array's length, and the sum accumulates as you go. Two details decide whether the answer is right:
- Empty input has no mean. Check for it before dividing and return
0.0. - Round once, at the end. Rounding each element or a partial sum changes the answer; only the final quotient is rounded to 2 decimal places.
Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 2985: Calculate Compressed Mean Solution & Explanation
Problem Overview
TL;DR: Sum the quantities in one pass, divide by how many there are, and round to 2 decimal places ( time, space). An empty array returns 0.0.
You are given an integer array quantities, where quantities[i] is the number of items in the i-th order. Return the mean (average) number of items per order, rounded to 2 decimal places. If there are no orders, return 0.0.
On LeetCode this is a database problem: the orders arrive compressed as rows of (item_count, order_occurrences), and the answer is ROUND(SUM(item_count * order_occurrences) / SUM(order_occurrences), 2). Here every order is listed individually, so the same answer is simply the mean of the array.
Brute Force Approach for Calculate Compressed Mean
There is no meaningfully slower approach — the answer depends on every element, so any correct solution reads all of them. The only "brute force" mistake is doing more work than needed, such as sorting first or building a copy:
1# Correct, but does unnecessary work
2def wasteful(quantities):
3 if not quantities:
4 return 0.0
5 ordered = sorted(quantities) # O(N log N) for nothing
6 return round(sum(ordered) / len(ordered), 2)Time Complexity: because of the sort, which the mean does not need.
Algorithm Strategy: Sliding Window Patterns
- If
quantitiesis empty, return0.0. - Add every quantity to a running
total(use a 64-bit integer in typed languages; up to values of up to overflow 32 bits). - Divide
totalby the number of orders as floating point. - Round the quotient to 2 decimal places and return it.
Execution Flow
Let's trace quantities = [1, 1, 2, 2, 1, 1].
- Not empty, so continue.
- Sum:
1 + 1 + 2 + 2 + 1 + 1 = 8. - Divide:
8 / 6 = 1.3333... - Round:
1.33.
And quantities = [2, 2, 3, 3, 4, 5, 5, 4]: the sum is 28, and 28 / 8 = 3.5, which is already exact to 2 decimal places.
Proof of Correctness
The mean of values is defined as their sum divided by . The loop visits every element exactly once and adds it to total, so after the loop total is the exact sum (integer arithmetic, no rounding), and dividing by gives the exact mean up to floating-point precision. Rounding is applied once, to that value, which is what the problem asks for. The empty case is handled before the division, so there is never a division by zero.
Pattern Reuse Notes
- The running-sum bookkeeping here is the core of every fixed-size sliding window: "Maximum Average Subarray I" keeps the same sum but over a window of length
k, adding the entering element and subtracting the leaving one. - "Round the aggregate once, at the end" applies to any average or ratio problem (e.g. "Maximum Average Pass Ratio").
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 2985
1class Solution {
2public:
3 double calculateCompressedMean(vector<int>& quantities) {
4 if (quantities.empty()) {
5 return 0.0;
6 }
7
8 double total = accumulate(quantities.begin(), quantities.end(), 0LL);
9 double mean = total / quantities.size();
10
11 // Round to 2 decimal places
12 return round(mean * 100) / 100.0;
13 }
14};Java Solution for LeetCode 2985
1class Solution {
2 public double calculateCompressedMean(int[] quantities) {
3 if (quantities == null || quantities.length == 0) {
4 return 0.0;
5 }
6 long sum = 0;
7 for (int q : quantities) {
8 sum += q;
9 }
10 double mean = (double) sum / quantities.length;
11
12 // Round to 2 decimal places
13 return Math.round(mean * 100) / 100.0;
14 }
15}Python Solution for LeetCode 2985
1from typing import List
2
3class Solution:
4 def calculateCompressedMean(self, quantities: List[int]) -> float:
5 if not quantities:
6 return 0.0
7 return round(sum(quantities) / len(quantities), 2)