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:

  1. If the number of elements in the stream is less than m, the MKAverage is -1.
  2. Otherwise, copy the last m elements of the stream to a separate container.
  3. Remove the smallest k elements and the largest k elements from the container.
  4. 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 integers m and k.
  • void addElement(int num) Inserts a new element num into 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
Finding MK Average: Stream Processing with m=3, k=1Stream:3110555Last m=3Sorted:555Remove k=1 extremes:555SkipKeepSkipMK Average = 5 ÷ 1 = 5
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
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen