Finding MK Average Problem
Description
LeetCode Problem 1825.
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
- If the number of the elements in the stream is less than
myou should consider the MKAverage to be-1. Otherwise, copy the lastmelements of the stream to a separate container. - Remove the smallest
kelements and the largestkelements from the container. - Calculate the average value for the rest of the elements rounded down to the nearest integer.
Implement the MKAverage class:
MKAverage(int m, int k)Initializes the MKAverage object with an empty stream and the two integersmandk.void addElement(int num)Inserts a new elementnuminto the stream.int calculateMKAverage()Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.
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
MKAverage obj = new MKAverage(3, 1);
obj.addElement(3); // current elements are [3]
obj.addElement(1); // current elements are [3,1]
obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.
obj.addElement(10); // current elements are [3,1,10]
obj.calculateMKAverage(); // The last 3 elements are [3,1,10].
// After removing smallest and largest 1 element the container will be [3].
// The average of [3] equals 3/1 = 3, return 3
obj.addElement(5); // current elements are [3,1,10,5]
obj.addElement(5); // current elements are [3,1,10,5,5]
obj.addElement(5); // current elements are [3,1,10,5,5,5]
obj.calculateMKAverage(); // The last 3 elements are [5,5,5].
// After removing smallest and largest 1 element the container will be [5].
// The average of [5] equals 5/1 = 5, return 5
Constraints:
3 <= m <= 10^51 < k*2 < m1 <= num <= 10^5- At most
10^5calls will be made toaddElementandcalculateMKAverage.
Solution
Approach: Fenwick Tree over Values
Only the last m numbers count, and the average drops the k smallest and k largest of them. Because every number is at most 105, we can index by value instead of keeping sorted containers.
Keep two Fenwick (binary indexed) trees over the values 1 .. 10^5: one stores how many times each value occurs in the window and the other stores the sum of those occurrences. Also keep a queue with the last m numbers.
addElement(num)pushesnuminto the queue and the trees. If the queue now holds more thanmnumbers, the oldest one is removed from both.- To get the sum of the
tsmallest numbers in the window, descend the tree from its highest bit: take a whole block whenever its count still fits withint, and finish with the remaining copies of the next value. calculateMKAverage()returns-1while fewer thanmnumbers have arrived. Otherwise the sum of the middle numbers issmallest(m - k) - smallest(k), and the answer is that sum divided bym - 2k, rounded down.
Complexity: O(log V) time per call, where V = 105 is the largest value, and O(V + m) space.
from collections import deque
class MKAverage:
N = 1 << 17
def __init__(self, m: int, k: int):
self.m = m
self.k = k
self.q = deque()
self.c = [0] * (self.N + 1)
self.s = [0] * (self.N + 1)
def _update(self, x: int, d: int) -> None:
v = x
while v <= self.N:
self.c[v] += d
self.s[v] += d * x
v += v & -v
def _smallest_sum(self, t: int) -> int:
pos = acc = 0
pw = self.N
while pw:
if pos + pw <= self.N and self.c[pos + pw] <= t:
pos += pw
t -= self.c[pos]
acc += self.s[pos]
pw >>= 1
return acc + t * (pos + 1)
def addElement(self, num: int) -> None:
self.q.append(num)
self._update(num, 1)
if len(self.q) > self.m:
self._update(self.q.popleft(), -1)
def calculateMKAverage(self) -> int:
if len(self.q) < self.m:
return -1
total = self._smallest_sum(self.m - self.k) - self._smallest_sum(self.k)
return total // (self.m - 2 * self.k)