15% off all plans & roadmaps Use code
See plansCalculate Compressed Mean
- LeetCode 2985
- Easy
- Sliding Window
- Fixed Size (Subarray Calculation)
Updated
TL;DR: Find the average of the array and round it to 2 decimal places, returning 0.0 for an empty array. Add every value into one running total, then divide once and round only the final result.
Problem
You are given an integer array quantities. The value 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 quantities is empty, return 0.0.
This is the array form of LeetCode 2985. In that problem the orders arrive compressed as (item_count, order_occurrences) rows. Here every order is listed on its own.
Example 1
Input: quantities = [2,2,3,3,4,5,5,4] Output: 3.5 Explanation: The eight orders hold 28 items in total. 28 / 8 = 3.5, which is already exact at two decimal places.
Constraints
0 <= quantities.length <= 10^51 <= quantities[i] <= 10^6
Constraints that matter
- Up to 10^5 values of up to 10^6 can sum to 10^11, which overflows a 32-bit int. Keep the running total in a 64-bit integer.
- The mean depends on every element, so no correct method can skip values. One read per element, which is O(n), is the floor.
- The array can be empty, so the code must check the length before it divides.
- The answer must round to 2 decimal places. Rounding on exact halves needs integer arithmetic to be predictable, so the solution avoids float rounding.
Hints
Hint 1
The mean is the total divided by the count, and both numbers come from one walk over the array.
Hint 2
A beginner often sorts the array or copies it first.
Solution
Intuition
The mean is the total divided by the count, and both numbers come from one walk over the array. You keep a single number that grows as you read each element. The answer covers the whole array, so the window is the whole array and you never revisit an element, which is the fixed-size sliding window pattern in its simplest form.
Picture a tally counter at a turnstile: each person who walks past adds one to the count, and you read the counter once at the end. The running total is the counter, each array element is one person, and you never revisit anyone.
The answer depends on every value. Changing any single quantity changes the mean, so you cannot skip elements and stay correct. That sets the floor at one read per element. Sorting does not help, because the sum does not depend on order. Sorting only adds O(n log n) work for nothing.
The harder part is rounding. Round only the final quotient, and round half up, the way school arithmetic does. Python's built-in round on a float rounds exact halves to the even digit, so round(0.125, 2) gives 0.12 instead of 0.13. Working in hundredths with integers avoids that trap and keeps the result exact.
Worked example
Input: quantities = [2, 2, 3, 3, 4, 5, 5, 4] Output: 3.5 Explanation: The eight orders hold 28 items together. Dividing 28 by 8 gives exactly 3.5, so no rounding changes the value. The walkthrough below traces the running total step by step.
The Fixed Size (Subarray Calculation) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Fixed Size (Subarray Calculation)
Part of Sliding Window
Approach 1: Single pass sum, integer roundingOptimalFixed Size (Subarray Calculation)
A beginner often sorts the array or copies it first. Sorting costs O(n log n) and gives no benefit, because addition is order-independent. The fix is to add each value into one running total as you read it, then divide once.
The division needs care. Instead of dividing as floats and calling round, compute the answer in hundredths using integer arithmetic. For non-negative total and n, the mean times 100 rounded half up equals floor((200 * total + n) / (2 * n)). Only integer operations appear in that formula, so the result is exact.
Why it is correct. The running total always equals the exact sum of every element read so far, so the final total is the exact sum of the whole array. The expression (200 * total + n) / (2 * n) equals 100 * mean + 0.5, so flooring it rounds the hundredths half up. Integer arithmetic keeps every step exact, so no float error can push a tie to the wrong side.
Steps
- If the array is empty, return 0.0 before doing any division.
- Set n to the length of the array and total to 0, stored in a 64-bit integer.
- Loop over every quantity once and add it to total.
- Compute hundredths = (200 * total + n) // (2 * n). This is the mean times 100, rounded half up.
- Return hundredths / 100 as a floating point number.
Dry run
The example has n = 8. The table tracks the running total after each element.
| Step | quantity | total | n | Note |
|---|---|---|---|---|
| start | none | 0 | 8 | Array is not empty |
| 1 | 2 | 2 | 8 | |
| 2 | 2 | 4 | 8 | |
| 3 | 3 | 7 | 8 | |
| 4 | 3 | 10 | 8 | |
| 5 | 4 | 14 | 8 | |
| 6 | 5 | 19 | 8 | |
| 7 | 5 | 24 | 8 | |
| 8 | 4 | 28 | 8 | Loop ends |
| finish | none | 28 | 8 | hundredths = (200 * 28 + 8) // 16 = 5608 // 16 = 350 |
The function returns 350 / 100 = 3.5, which matches the expected output.
For a case with a rounding decision, take [1, 1, 2]. The total is 4 and n is 3. The mean is 1.333..., so hundredths = (200 * 4 + 3) // 6 = 803 // 6 = 133, and the answer is 1.33.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of quantities. The loop body runs once per element and does one addition, so the loop performs n constant-time steps. The empty check, the multiplication and the single integer division each take constant time, so the total work is O(n). The solution stores only n, total and hundredths, and each of those is one fixed-size number no matter how long the array is, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def calculateCompressedMean(self, quantities: List[int]) -> float:
n = len(quantities)
if n == 0:
return 0.0
total = sum(quantities)
# Mean times 100, rounded half up, using integers only
hundredths = (200 * total + n) // (2 * n)
return hundredths / 100Common mistakes
total / nwith two integers in Java, C++ or C#. Integer division truncates, so 8 / 6 becomes 1. Use the integer hundredths formula, or cast one operand to a floating point type before dividing.int totalin Java, C++ or C#. Ten to the fifth values of up to ten to the sixth sum to 10^11, which wraps around in 32 bits. Keep the total inlongorlong long.n == 0checked after the division. Python raises ZeroDivisionError and JavaScript returns NaN. Check the length first and return 0.0.round(total / n, 2)in Python. Python rounds exact halves to even, so round(0.125, 2) returns 0.12 where half-up gives 0.13. The integer formula rounds half up on every input.- Rounding inside the loop or rounding partial sums. Each early rounding moves the answer. Round only the final quotient.
Edge cases
- An empty array returns 0.0 and never reaches the division.
- A single value such as [7] returns 7.0, because the total and the count are both easy to read.
- All values equal, such as [4, 4, 4], returns 4.0.
- An exact half at the second decimal, such as [3, 3, 3, 3, 4, 4, 4, 5] with sum 29 and n = 8, returns 3.63. Plain round() in Python would return 3.62.
- The largest input, 10^5 copies of 10^6, has a total of 10^11 and returns 1000000.0. This case fails only when the total is stored in a 32-bit type.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Calculate Compressed Mean, with how to answer them.
Unlock the follow-upsCalculate Compressed Mean FAQ
What is the time complexity of Calculate Compressed Mean?
The time complexity is O(n), where n is the length of the array. The loop reads each element once and does constant work per element. The empty check and the final division take constant time.
Why use a running sum for Calculate Compressed Mean?
The mean is the sum divided by the count, and the count is the length. A running sum builds the sum in one pass without storing the values. Sorting or copying the array adds work that the answer does not need.
Can Calculate Compressed Mean be solved in O(1) extra space?
Yes. The solution stores only the length, the total and the rounded hundredths, so the extra space is O(1). Any correct method still reads all n values, so the time stays O(n).
Why avoid round() in Python?
Python's round() rounds exact halves to the even digit, so round(0.125, 2) returns 0.12. The integer formula rounds half up on every input, which matches the expected output on exact halves.
Is the array version the same as LeetCode 2985?
The database version gives rows of item_count and order_occurrences and computes the sum of their products divided by the sum of the occurrences, rounded to 2 decimals. The array version lists every order on its own, so the answer is the plain mean of the array.
Asked at
See which companies ask this — Pro
Related problems
- Moving Average from Data Stream · same technique: Fixed Size (Subarray Calculation)
- Maximum Average Subarray I · same technique: Fixed Size (Subarray Calculation)
- Find X-Sum of All K-Long Subarrays I · same technique: Fixed Size (Subarray Calculation)
- Find the Power of K-Size Subarrays I · same technique: Fixed Size (Subarray Calculation)
- Contains Duplicate II · same pattern: Sliding Window
- Longest Substring Without Repeating Characters · same pattern: Sliding Window
- Longest Repeating Character Replacement · same pattern: Sliding Window
- Permutation in String · same pattern: Sliding Window
- Minimum Size Subarray Sum · same pattern: Sliding Window
- Longest Turbulent Subarray · same pattern: Sliding Window