Finding MK Average - Problem
You are given two integers, m and k, and a stream of integers. You need to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
- If the number of elements in the stream is less than
m, the MKAverage is-1. - Otherwise, copy the last
melements of the stream to a separate container. - Remove the smallest
kelements and the largestkelements from the container. - Calculate the average value for the remaining 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.
Input & Output
Example 1 — Basic Operations
$
Input:
MKAverage(3, 1), addElement(3), addElement(1), addElement(10), addElement(5), addElement(5), addElement(5), calculateMKAverage()
›
Output:
[null, null, null, null, null, null, null, 5]
💡 Note:
After adding [3,1,10,5,5,5], last 3 elements are [5,5,5]. Remove 1 smallest and 1 largest: middle element is 5, so average is 5.
Example 2 — Insufficient Elements
$
Input:
MKAverage(3, 1), addElement(3), addElement(1), calculateMKAverage()
›
Output:
[null, null, null, -1]
💡 Note:
Only 2 elements in stream, but need m=3 elements minimum, so return -1.
Example 3 — Different Values
$
Input:
MKAverage(5, 2), addElement(3), addElement(1), addElement(12), addElement(5), addElement(3), addElement(4), calculateMKAverage()
›
Output:
[null, null, null, null, null, null, null, 4]
💡 Note:
Last 5 elements: [1,12,5,3,4]. Sorted: [1,3,4,5,12]. Remove 2 smallest [1,3] and 2 largest [5,12]. Middle: [4]. Average = 4.
Constraints
- 1 ≤ m ≤ 105
- 1 ≤ k*2 < m
- 1 ≤ num ≤ 105
- At most 105 calls to addElement and calculateMKAverage
Visualization
Tap to expand
Understanding the Visualization
1
Stream Input
Elements arrive: 3, 1, 10, 5, 5, 5
2
Last m=3
Take last 3 elements: [5, 5, 5]
3
Remove Extremes
Remove k=1 smallest and largest: middle = [5]
4
Calculate Average
Average of middle elements = 5
Key Takeaway
🎯 Key Insight: Use balanced data structures to efficiently maintain sorted sliding window for fast extreme removal and average calculation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code