KatInterview

Rolling Window Mean After Dropping the Largest k

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchsliding-windowfenwick-treeorder-statistics

Last 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:

  1. Remove the k largest 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.
  2. Compute the arithmetic mean of the remaining w - k elements.

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 - k values divided by w - 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^5
  • 0 <= nums[i] <= 10^6
  • 1 <= 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.