Rolling Window Mean After Dropping the Largest k
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Compute the mean of each fixed-size window after discarding its k largest values, which needs a structure that supports fast insertion, deletion and sum-of-smallest queries.
Rolling Window Mean After Dropping the Largest k
You are given a list of non-negative integers nums, a window length w, and a number k of elements to discard from every window.
Slide a window of length w across nums from left to right, one position at a time. This gives len(nums) - w + 1 windows. For each window:
- Remove the
klargest elements of that window. If several elements are equal, it does not matter which copies are removed, because only the sum of what remains is used. - Compute the arithmetic mean of the remaining
w - kelements.
Return the means in window order, as floats.
Function
Implement trimmed_window_means(nums, w, k), which returns a List[float] of length len(nums) - w + 1.
Details
- When
k = 0, nothing is removed and each result is the ordinary mean of its window. - When
k = w - 1, only the smallest element of each window remains. - Each mean is the sum of the remaining
w - kvalues divided byw - k. - A simple solution that sorts every window is too slow for the largest inputs. Aim for roughly
O(n log n)time.
Constraints
1 <= len(nums) <= 10^50 <= nums[i] <= 10^61 <= w <= len(nums)0 <= k < w, so at least one element always remains in each window.
Examples
Example 1
Input: trimmed_window_means([10, 20, 30, 40, 50], 3, 1)
Output: [15, 25, 35]
Example 2
Input: trimmed_window_means([1, 2, 3, 4, 5, 6], 4, 0)
Output: [2.5, 3.5, 4.5]
Example 3
Input: trimmed_window_means([5, 5, 5, 5], 3, 2)
Output: [5, 5]
Hints
Hint 1
Removing the k largest elements is the same as keeping the w - k smallest ones. Rephrase the task as the sum of the m smallest values in the window, where m = w - k.
Hint 2
You need a structure that supports insert, delete and sum of the m smallest. Options are two multisets or heaps with a running sum, or a Fenwick tree over compressed values.
Hint 3
With a Fenwick tree, store a count and a sum at each value rank. Walk down the tree to find the largest prefix holding fewer than m elements. Then fill the shortfall with copies of the next value, which handles duplicates.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Dropping the k largest elements of a window of size w leaves its m = w - k smallest elements. Each answer is therefore (sum of the m smallest values in the window) / m.
So we need a structure over the current window that supports three operations quickly:
- insert a value,
- delete a value,
- return the sum of the
msmallest values.
A Fenwick tree (binary indexed tree) over compressed values does this:
- Sort the distinct values of
numsand give each a 1-based rank. - Keep two Fenwick trees indexed by rank. One stores how many window elements have that rank, and the other stores the sum of those elements.
- When the window slides, add the new element and remove the one that left.
- To get the sum of the
msmallest, descend the tree from the highest power of two. Move to a new position only if the accumulated count stays strictly belowm. This finds the largest rank prefixposthat contains fewer thanmelements, along with its countcand sums. - The
m-th smallest element then has rankpos + 1, which isvals[pos]. The remainingm - celements needed are all equal to that value, so the result iss + (m - c) * vals[pos].
Why it is correct
- Each element is inserted once when it enters the window and deleted once when it leaves, so the trees always describe exactly the current window (the query happens after the deletion).
- The descent is the standard Fenwick order-statistic search, carrying sums along with counts.
- Duplicates are handled by the
(m - c) * vals[pos]term. If the boundary falls inside a run of equal values, exactly the needed number of copies is counted, and which copies are "dropped" does not change the sum. - Edge cases need no special handling. With
k = 0,m = wand the result is the plain sliding mean. Withk = w - 1,m = 1and the result is the window minimum.
Complexity
- Time:
O(n log n). Sorting isO(n log n), and each of thensteps does at most two updates and one query, eachO(log n). - Space:
O(n)for the rank map and the two trees, plus the output list.
Reference solution
from typing import List
def trimmed_window_means(nums: List[int], w: int, k: int) -> List[float]:
vals = sorted(set(nums))
rank = {v: i + 1 for i, v in enumerate(vals)}
size = len(vals)
cnt = [0] * (size + 1)
tot = [0] * (size + 1)
top = 1 << size.bit_length()
def update(i: int, dc: int, ds: int) -> None:
while i <= size:
cnt[i] += dc
tot[i] += ds
i += i & -i
def smallest_sum(m: int) -> int:
pos = 0
c = 0
s = 0
step = top
while step:
nxt = pos + step
if nxt <= size and c + cnt[nxt] < m:
pos = nxt
c += cnt[nxt]
s += tot[nxt]
step >>= 1
# rank pos + 1 holds the m-th smallest value, i.e. vals[pos]
return s + (m - c) * vals[pos]
m = w - k
result: List[float] = []
for i, x in enumerate(nums):
update(rank[x], 1, x)
if i >= w:
old = nums[i - w]
update(rank[old], -1, -old)
if i >= w - 1:
result.append(smallest_sum(m) / m)
return result