Problem
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
m
you should consider the MKAverage to be-1
. Otherwise, copy the lastm
elements of the stream to a separate container. - Remove the smallest
k
elements and the largestk
elements 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 integersm
andk
.void addElement(int num)
Inserts a new elementnum
into the stream.int calculateMKAverage()
Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.
Examples
Example 1
|
|
Constraints
3 <= m <= 10^5
1 <= k*2 < m
1 <= num <= 10^5
- At most
105
calls will be made toaddElement
andcalculateMKAverage
.
Solution
Method 1 – Multiset/SortedList Partitioning
Intuition
To efficiently maintain the last m elements and quickly remove the k smallest and k largest, we use three multisets (or sorted lists): one for the k smallest, one for the k largest, and one for the middle elements. As new elements are added and old ones removed, we rebalance these multisets to always keep the correct partition.
Approach
- Use a queue to store the last m elements.
- Use three multisets (or sorted lists):
- left: k smallest elements
- right: k largest elements
- mid: the rest (m - 2k elements)
- When adding a new element:
- Add it to the appropriate multiset.
- If the queue exceeds m, remove the oldest element and rebalance.
- Always maintain the sizes: left and right have k elements each, mid has m-2k.
- To calculate MKAverage:
- If less than m elements, return -1.
- Otherwise, return the integer average of the mid set.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log m)
per operation, since each insertion/removal in a SortedList/TreeMap is logarithmic in m. - 🧺 Space complexity:
O(m)
, for storing the last m elements and the three multisets.