15% off all plans & roadmaps Use code
See plansFinding MK Average
- LeetCode 1825
- Hard
- Heap (Priority Queue) Patterns
- Two Heaps for Median Finding
Updated
TL;DR: You must average the middle m - 2k values of a sliding window of the last m values, rounded down. Keep a Fenwick tree over the values 1 to 10^5 so you can sum the smallest values in O(log V) per call.
Problem
You receive two integers, m and k, and then a stream of integers. Build a data structure that reports the MKAverage of the stream.
The MKAverage is found in three steps:
- If the stream holds fewer than
melements, the MKAverage is-1. Otherwise, copy the lastmelements into a separate container. - Remove the smallest
kand the largestkelements from that container. - Average the remaining elements and round the result down to the nearest integer.
Implement the MKAverage class:
MKAverage(int m, int k)creates the object with an empty stream and the two integers.void addElement(int num)appendsnumto the stream.int calculateMKAverage()returns the MKAverage of the current stream, rounded down.
Example 1
Input: ["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"] [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []] Output: [null, null, null, -1, null, 3, null, null, null, 5] Explanation: Create the object with m = 3 and k = 1. Add 3 and 1. The stream holds two values, which is fewer than m, so the result is -1. After adding 10, the last three values are [3, 1, 10]. Removing the smallest (1) and the largest (10) leaves [3], so the answer is 3. After adding three 5s, the last three values are [5, 5, 5], and the answer is 5.
Constraints
3 <= m <= 10^51 < k * 2 < m1 <= num <= 10^5- At most
10^5calls will be made toaddElementandcalculateMKAverage.
Constraints that matter
- The window holds up to 10^5 values, so sorting it on every call (m log m per call) is too slow when there are 10^5 calls.
- Values are integers from 1 to 10^5. That small, fixed range lets you keep a counter per value and avoid sorting.
- k * 2 < m means the middle band always has at least one value, so the division by m - 2k never hits zero.
- Sums can reach about 10^10 (10^5 values of size 10^5), so Java and C# need 64-bit integers for the sums.
Hints
Hint 1
The problem asks for an average over a sliding window of the last m values.
Hint 2
Keep every value in a list.
Solution
Intuition
The problem asks for an average over a sliding window of the last m values. You trim the window by value, not by position, so the middle band changes whenever a value enters or leaves. This is an order-statistics problem on a sliding window, the same family as the two heaps for median finding pattern.
Picture a row of numbered bins, one per value from 1 to 100000, where each bin holds a tally of how many window values equal it. The Fenwick tree is that bin row, adding a value drops a token into its bin, and removing the oldest pulls one back out.
You must remove the oldest value when the window slides. A plain heap returns its top quickly but cannot delete a value from the middle. Three heaps with lazy deletion can work, but you must track which heap holds each expired value, and that bookkeeping gets messy fast.
A Fenwick tree (binary indexed tree) over the value range solves this. Each value from 1 to 10^5 owns a slot, so adding or removing a value is a point update. The sum of the t smallest values is one walk down the tree, so the window never needs sorting.
Worked example
Input: m = 5, k = 1. Then addElement(1), addElement(2), addElement(3), addElement(4), addElement(5), and calculateMKAverage(). Output: 3 Explanation: After five adds the window is the whole stream, [1, 2, 3, 4, 5]. Drop the smallest value (1) and the largest value (5). The middle is [2, 3, 4], which sums to 9. Nine divided by three is 3.
Approach 1: Brute force: copy and sort the window
Keep every value in a list. On each call, take the last m values, sort them, drop the first k and last k, and average what remains. This follows the statement exactly, but each call re-sorts the window from scratch, even though only one value changed since the last call.
Steps
- Append every added value to a list, in arrival order.
- In calculateMKAverage, return -1 if the list holds fewer than m values.
- Copy the last m values into a new array.
- Sort the copy in ascending order.
- Sum the entries from index k up to index m - k, not including m - k.
- Divide the sum by m - 2k and round down.
Dry run
Use m = 5, k = 1, and the stream 1, 2, 3, 4, 5, so the window is the whole list. Sorting leaves [1, 2, 3, 4, 5] unchanged. Indices 1 to 3 hold [2, 3, 4], because index 0 and index 4 are dropped. The sum is 9, and 9 divided by 3 is 3, which matches the output.
Complexity
| Time | O(m log m) per calculateMKAverage call |
|---|---|
| Space | O(Q) for the stored values, where Q is the number of calls |
Let n be the number of values added so far and m the window size. Each call copies m values and sorts them with O(m log m) comparisons, then scans at most m values, so one call costs O(m log m). addElement only appends, which costs O(1) amortized. Storing every value takes O(n) space, and n can reach 10^5.
PythonTested in our runner
from typing import List, Optional
class MKAverage:
def __init__(self, m: int, k: int):
self.m = m
self.k = k
self.stream: List[int] = []
def addElement(self, num: int) -> None:
self.stream.append(num)
def calculateMKAverage(self) -> int:
if len(self.stream) < self.m:
return -1
# Copy the last m values and sort them
window = sorted(self.stream[-self.m:])
middle = window[self.k:self.m - self.k]
return sum(middle) // len(middle)
The Two Heaps for Median Finding 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
Two Heaps for Median Finding
Part of Heap (Priority Queue) Patterns
Approach 2: Fenwick tree over values (order statistics)OptimalTwo Heaps for Median Finding
What is slow: the brute force sorts m values on every call, and the sort repeats work that barely changed. The insight that fixes it: the answer needs only sums of the smallest values, and the window changes by one value per call. Keep a count and a sum for every possible value in two Fenwick trees, so each add or remove touches one path of about 17 nodes.
The middle band is the smallest m - k values minus the smallest k values. Both sums come from one walk down the count tree, using the same descent, so no sorting or separate largest-k query is needed.
Why it is correct. The two trees always hold exactly the values in the deque, so every count and sum reflects the current window. Sorted by value, the t smallest values are the first t entries, and the descent stops at the last value that fits. Subtracting the k smallest sum from the m - k smallest sum leaves exactly the middle m - 2k values.
Steps
- Keep a deque of the last m values in arrival order.
- Keep two Fenwick arrays over values 1 to 100000: one for counts and one for sums.
- In addElement, add the value to both trees. If the deque now holds m + 1 values, pop the oldest and subtract it from both trees.
- Write sumSmallest(t): descend the count tree from step 2^16 to find the largest position whose prefix count is below t, then add the leftover copies of the next value.
- In calculateMKAverage, return -1 if the deque holds fewer than m values.
- Compute midSum as sumSmallest(m - k) minus sumSmallest(k).
- Return midSum divided by m - 2k, rounded down.
Dry run
Start from the example: m = 5, k = 1, and the values 1 to 5 added in order. The count tree holds one copy each of 1 through 5. The window never exceeds five values, so nothing expires. The table traces the state at each call.
| Call | Window (oldest first) | sumSmallest(4) | sumSmallest(1) | Result |
|---|---|---|---|---|
| addElement(1) | [1] | not needed | not needed | below m, no answer |
| addElement(2) | [1, 2] | not needed | not needed | below m, no answer |
| addElement(3) | [1, 2, 3] | not needed | not needed | below m, no answer |
| addElement(4) | [1, 2, 3, 4] | not needed | not needed | below m, no answer |
| addElement(5) | [1, 2, 3, 4, 5] | not needed | not needed | full, nothing expires |
| calculateMKAverage() | [1, 2, 3, 4, 5] | 1 + 2 + 3 + 4 = 10 | 1 | (10 - 1) // (5 - 2) = 3 |
For t = 4, the descent stops at position 3. The prefix count there is 3, which is below 4, and the prefix sum is 6. The leftover is one copy of value 4, so the result is 6 + 1 * 4 = 10. The output is 3, which matches the expected value.
Complexity
| Time | O(log V) per call, where V = 100000 is the largest value |
|---|---|
| Space | O(V + m), where V is the fixed value bound and m is the window size |
Let V = 100000 be the largest value and m the window size. addElement updates at most 17 nodes in each Fenwick tree, because the update path length is at most log2(V) + 1. calculateMKAverage runs two descents, and each descent loops over the 17 powers of two from 2^16 down to 1, so it costs O(log V). The arrays hold V + 1 entries each, and the deque holds at most m + 1 values, so the space is O(V + m).
PythonTested in our runner
from typing import List, Optional
from collections import deque
class MKAverage:
MAX_VALUE = 100000
def __init__(self, m: int, k: int):
self.m = m
self.k = k
self.window = deque()
self.count_tree = [0] * (self.MAX_VALUE + 1)
self.sum_tree = [0] * (self.MAX_VALUE + 1)
def _update(self, value: int, sign: int) -> None:
# Point update on both Fenwick trees
i = value
while i <= self.MAX_VALUE:
self.count_tree[i] += sign
self.sum_tree[i] += sign * value
i += i & -i
def _sum_smallest(self, t: int) -> int:
# Sum of the t smallest stored values
if t <= 0:
return 0
pos = 0
remaining = t
acc = 0
step = 1 << 16
while step:
nxt = pos + step
if nxt <= self.MAX_VALUE and self.count_tree[nxt] < remaining:
pos = nxt
remaining -= self.count_tree[nxt]
acc += self.sum_tree[nxt]
step >>= 1
# The next value (pos + 1) supplies the leftover copies
return acc + remaining * (pos + 1)
def addElement(self, num: int) -> None:
self.window.append(num)
self._update(num, 1)
if len(self.window) > self.m:
self._update(self.window.popleft(), -1)
def calculateMKAverage(self) -> int:
if len(self.window) < self.m:
return -1
mid_sum = self._sum_smallest(self.m - self.k) - self._sum_smallest(self.k)
return mid_sum // (self.m - 2 * self.k)
Common mistakes
- Forgetting to remove the expired value. If
addElementnever callsupdate(old, -1), the trees hold the whole stream and the answer drifts. Pop the oldest value and subtract it whenever the deque grows pastm. - Dividing by
minstead ofm - 2 * k. The middle band has m minus k minus k values, so the divisor must bem - 2 * k. - Subtracting only the smallest k from the total. Keeping the largest k in the sum gives a wrong answer. Use
sumSmallest(m - k) - sumSmallest(k), which removes both ends with two queries of the same kind. - Starting the descent below 2^16. A step of 2^15 or less cannot reach values near 10^5, so large values are missed. Start at
1 << 16, the highest power of two at or below 10^5. - Using the value instead of the position in the leftover term. The leftover copies belong to the value
pos + 1, soremaining * posis wrong. Useremaining * (pos + 1). - Overflow in Java and C#. Sums reach about 10^10, which does not fit in a 32-bit int. Keep the sum trees, the accumulator and midSum as
long.
Edge cases
- Two values with m = 3 returns -1, because the window is not full. Exactly m values returns the average of the middle band.
- m = 3, k = 1 with values 3, 1, 10 gives middle [3], so the answer is 3. A single middle value is a valid case.
- Five copies of 5 with m = 5 and k = 2 gives middle [5], so the answer is 5. Duplicates are counted one by one in the tree.
- Values 1 and 100000 in the same window force the descent to reach the top of the value range. A wrong starting step fails here.
- Values 1 to 6 with m = 5 and k = 1: after the sixth add, value 1 expires. The window is [2, 3, 4, 5, 6], the middle is [3, 4, 5], and the answer is 4.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Finding MK Average, with how to answer them.
Unlock the follow-upsFinding MK Average FAQ
What is the time complexity of Finding MK Average?
The Fenwick solution runs in O(log V) per call, where V = 100000 is the largest value. That is about 17 steps per call. The brute force sort costs O(m log m) per calculateMKAverage call.
Why use a Fenwick tree for Finding MK Average?
The values are small integers, so each value gets its own counter. A Fenwick tree updates a counter and answers prefix sums in O(log V). It also lets you delete the oldest value directly, which a plain heap cannot do.
Can Finding MK Average be solved in O(1) extra space?
No, not with these methods. The window must be kept so the oldest value can be removed, which takes O(m) space in the worst case. The two Fenwick arrays add a fixed size of about 2 * 10^5 slots on top of that.
Is a heap enough for Finding MK Average?
A single heap is not enough, because the oldest value can sit anywhere in the structure. Two or three heaps with lazy deletion can work, but a Fenwick tree over the value range keeps the bookkeeping simpler.
Why does the answer use floor division?
The statement rounds down. Every stored value is positive, so the sum is never negative. Integer division in Python, Java, C++, Go and C# then gives the floor, and Math.floor does the same in JavaScript.
Asked at
See which companies ask this — Pro
Related problems
- Find Median from Data Stream · same technique: Two Heaps for Median Finding
- Merge k Sorted Lists · same pattern: Heap (Priority Queue) Patterns
- Minimum Interval to Include Each Query · same pattern: Heap (Priority Queue) Patterns
- IPO · same pattern: Heap (Priority Queue) Patterns
- Meeting Rooms III · same pattern: Heap (Priority Queue) Patterns
- Smallest Range Covering Elements from K Lists · same pattern: Heap (Priority Queue) Patterns
- Minimum Cost to Hire K Workers · same pattern: Heap (Priority Queue) Patterns
- Top K Frequent Elements · same pattern: Heap (Priority Queue) Patterns
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Kth Largest Element in an Array · same pattern: Heap (Priority Queue) Patterns