Window Mean After Discarding the Top Values
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Compute the mean of every fixed-size window after removing its k largest entries, which requires an ordered structure that supports efficient insertion and deletion.
Trimmed Window Means
You are given a list of integers values, a window length size, and a number drop.
Consider every contiguous block of exactly size consecutive elements of values, moving from left to right. For each block, discard the drop largest elements and take the arithmetic mean of the size - drop elements that remain.
Rules:
- Equal numbers are separate elements. If a block contains the value
7three times and you must discard two of the largest, you discard exactly two of those occurrences and the third one stays (if it falls among the kept elements). - Which copy of a duplicate is discarded makes no difference to the result, since only the sum of the kept elements matters.
- If
dropis0, nothing is discarded and the result is the plain mean of the block. - The mean for a block is the sum of its kept elements divided by
size - drop.
Return a list with one mean per block, in order from the leftmost block to the rightmost. The list therefore has len(values) - size + 1 entries.
Function
trimmed_window_means(values: List[int], size: int, drop: int) -> List[float]
Constraints
1 <= size <= len(values) <= 200,0000 <= drop < size-10^6 <= values[i] <= 10^6- A solution that sorts every block from scratch is too slow for the upper limits.
Examples
Example 1
Input: trimmed_window_means([1, 5, 2, 8, 3], 3, 1)
Output: [1.5, 3.5, 2.5]
Example 2
Input: trimmed_window_means([4, 4, 4, 4], 2, 0)
Output: [4, 4, 4]
Example 3
Input: trimmed_window_means([7, 1, 9], 3, 2)
Output: [1]
Hints
Hint 1
For one block, the answer is the sum of its smallest size - drop elements divided by size - drop. Think about how to get that sum without sorting the whole block each time.
Hint 2
As the window moves, exactly one element leaves and one enters. Use a structure that supports insertion, deletion, and finding the m-th smallest element in logarithmic time, such as two heaps with lazy deletion or a Fenwick tree over compressed values.
Hint 3
With a Fenwick tree indexed by compressed value that stores counts and sums, find the position of the (size - drop)-th smallest element, add up everything strictly before it, and fill the remaining slots with copies of that boundary value so duplicates are handled correctly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Removing the drop largest elements of a window leaves its size - drop smallest elements, so each answer is the sum of the smallest keep = size - drop elements divided by keep.
Re-sorting every window costs about O(n * size * log size), which is too slow. Instead, keep a single ordered summary of the current window and update it as the window slides by one position (one element out, one in).
The summary used here is a pair of Fenwick (binary indexed) trees over the compressed values (the sorted distinct numbers in the input):
- one tree stores how many window elements have each value,
- the other stores the total sum contributed by each value.
For each window:
- Use a binary descent on the count tree to find the compressed position
pof thekeep-th smallest element. - Query the count and sum for all positions strictly before
p. Call thesebefore_cntandbefore_sum. - The remaining
keep - before_cntkept elements all equal the value at positionp, so the kept sum isbefore_sum + (keep - before_cnt) * distinct[p]. - Divide by
keepand record the result. - Slide: remove the outgoing element and add the incoming one in both trees.
Why it is correct
Elements are ordered by value, and the count tree lets us find the exact value v at rank keep. Every element with a value smaller than v is among the keep smallest, so their sum comes from the prefix query. The rest of the kept slots must be filled with copies of v (the window holds at least that many). Duplicates are therefore handled by counting, and it does not matter which copy of a tied value is considered discarded because the sum is identical.
When drop = 0, keep = size, and the formula gives the full window sum. When drop = size - 1, keep = 1, and the result is the window minimum.
Complexity
- Time:
O(n log n), for sorting the distinct values plusO(log n)per window for the rank search, the prefix queries, and the two updates. - Space:
O(n)for the compressed values and the two trees.
An equivalent approach uses a max-heap for the kept elements and a min-heap for the dropped ones, with lazy deletion and a running sum. It has the same time bound.
Reference solution
from typing import List
def trimmed_window_means(values: List[int], size: int, drop: int) -> List[float]:
distinct = sorted(set(values))
m = len(distinct)
pos_of = {v: i for i, v in enumerate(distinct)}
cnt_tree = [0] * (m + 1)
sum_tree = [0] * (m + 1)
def update(tree, index, delta):
index += 1
while index <= m:
tree[index] += delta
index += index & -index
def prefix(tree, end):
total = 0
while end:
total += tree[end]
end -= end & -end
return total
def kth(target):
# Returns the 0-based compressed position holding the target-th smallest element.
index = 0
bit = 1 << (m.bit_length() - 1)
while bit:
nxt = index + bit
if nxt <= m and cnt_tree[nxt] < target:
target -= cnt_tree[nxt]
index = nxt
bit >>= 1
return index
def change(v, delta):
p = pos_of[v]
update(cnt_tree, p, delta)
update(sum_tree, p, v * delta)
for v in values[:size]:
change(v, 1)
keep = size - drop
out = []
windows = len(values) - size + 1
for start in range(windows):
p = kth(keep)
before_cnt = prefix(cnt_tree, p)
before_sum = prefix(sum_tree, p)
extra = keep - before_cnt
kept_sum = before_sum + extra * distinct[p]
out.append(kept_sum / keep)
if start + 1 < windows:
change(values[start], -1)
change(values[start + size], 1)
return out