KatInterview

Window Mean After Discarding the Top Values

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchsliding-windowheapfenwick-tree

Last 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 7 three 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 drop is 0, 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,000
  • 0 <= 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.