Python 1093.py
class Solution:
def sampleStats(self, count: List[int]) -> List[float]:
low = 255
high = 0
median = 0
mode = 0
total = 0
sum_ = sum(count)
max_ = max(count)
mid1 = (sum_ + 1) // 2
mid2 = (sum_ + 2) // 2
seen = 0
for i, c in enumerate(count):
# min/max
if c != 0:
low = min(low, i)
high = max(high, i)
# mean
total += i * c
# median
if sum_ % 2 == 0:
if seen < mid1 <= seen + c:
median += i
if seen < mid2 <= seen + c:
median += i
seen += c
# mode
if c == max_:
mode = i
return [ low, high, total / sum_, median / (2 - (sum_ % 2)), mode ]
Difficulty
and has an acceptance rate of about 42% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Probability And Statistics
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes five statistical measures-minimum, maximum, mean, median, and mode-from a frequency array where the index represents a value and the element at that index indicates its occurrence count. The algorithm processes the input in a single pass, maintaining running aggregates that enable the final statistics to be derived without additional traversals.
Initialization
At the start, several accumulator variables are created with sentinel values.
low = 255
high = 0
median = 0
mode = 0
total = 0
sum_ = sum(count)
max_ = max(count)
mid1 = (sum_ + 1) // 2
mid2 = (sum_ + 2) // 2
seen = 0
low and high are initialized beyond the possible range of indices to ensure the first non-zero entry correctly updates them. sum_ holds the total number of observations, while max_ records the highest frequency to aid mode detection. mid1 and mid2 represent the target positions for median extraction, handling both odd and even total counts.
Minimum and Maximum
During the iteration, the algorithm updates the smallest and largest observed values whenever a non-zero count is encountered.
if c != 0:
low = min(low, i)
high = max(high, i)
Because low starts at a value larger than any possible index and high starts at zero, the first populated bucket correctly sets both extremes, and subsequent non-zero buckets adjust them as needed.
Mean Calculation
The mean is accumulated by adding the product of each value and its frequency to total.
total += i * c
After the loop, dividing total by sum_ yields the arithmetic mean. This approach avoids floating-point accumulation errors by performing the division only once at the end.
Median Determination
The median logic distinguishes between odd and even total counts using mid1 and mid2. The variable seen tracks the cumulative count of values processed so far.
if sum_ % 2 == 0:
if seen < mid1 <= seen + c:
median += i
if seen < mid2 <= seen + c:
median += i
seen += c
When the total number of observations is even, the median is the average of the two central values; mid1 and mid2 point to those positions. For an odd total, both mid1 and mid2 resolve to the same central index, causing the same value to be added twice. The final division by (2 - (sum_ % 2)) normalizes the sum to a single median value for odd totals and to the average of the two central values for even totals.
Mode Identification
The mode is the value whose frequency equals the maximum frequency found in the array. Because max_ is computed before the loop, each bucket can be compared directly.
if c == max_:
mode = i
If multiple values share the maximum frequency, the loop’s forward progression ensures the largest such value is retained, matching the problem’s specification that any mode is acceptable.
Edge Cases Handled
The code gracefully manages several boundary conditions.
When the input contains only zeros, sum_ becomes zero; however, the problem guarantees at least one non-zero entry, so the algorithm’s use of sum_ in division is safe.
If the smallest possible value (index 0) appears, low is immediately set to zero, overriding its initial sentinel.
When the largest possible value (index 255) appears, high is updated to 255, overriding its initial zero.
For a single observation, mid1 and mid2 both equal one, causing the median logic to add the sole value twice and the final division to reduce it to the correct single median.
When the frequency distribution is uniform, the mode logic will select the highest index with that frequency, which satisfies the requirement that any mode is acceptable.
Performance Optimizations
The implementation achieves optimal performance by consolidating all required statistics into a single linear scan of the frequency array.
Pre-computing sum_, max_, mid1, and mid2 eliminates the need for repeated calculations inside the loop, reducing overhead.
Using integer arithmetic for the median position checks (mid1 and mid2) avoids floating-point comparisons during iteration.
The final division for the median uses a conditional denominator (2 - (sum_ % 2)), which evaluates to either 1 or 2 without branching, ensuring a constant-time adjustment after the loop.
Overall, the algorithm runs in O(N) time where N is the length of the frequency array, with a minimal constant factor due to the tight loop and limited per-iteration work.
The memory footprint remains constant, as only a fixed set of scalar variables is allocated regardless of input size.
These choices together produce a solution that is both time-efficient and memory-efficient for the given problem constraints.
return [ low, high, total / sum_, median / (2 - (sum_ % 2)), mode ] ELI5 - Simplified Explanation
Imagine a big box of colorful blocks where each block has a number painted on it from zero to two hundred fifty-five. The computer is given a list that tells it how many of each block are sitting in the box.
First, the computer looks through all the blocks to find the smallest number, which it calls low, and the largest number, which it calls high. It keeps track of these as it explores the collection.
Next, it needs to find the average value of all the blocks. To do this, the computer adds up the values of every single block in the box and then divides that big pile by the total number of blocks. This gives the mean.
After that, it looks for the middle of the pack. If the blocks were all lined up in a long row from smallest to largest, the computer walks along the row until it reaches the middle spot to find the median value.
Finally, it searches for the mode, which is just the number that appears more often than any other number in the box. It finds the group that has the most blocks and picks that number as the winner.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 989: Add to Array-Form of Integer
- problem 993: Cousins in Binary Tree
- problem 1108: Defanging an IP Address
- problem 1006: Clumsy Factorial
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality