Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.k elements and the largest k elements from the container.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.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 <= 1051 < k*2 < m1 <= num <= 105105 calls will be made to addElement and calculateMKAverage.Problem summary: 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 last m elements of the stream to a separate container. Remove the smallest k elements and the largest k 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 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Design · Segment Tree
["MKAverage","addElement","addElement","calculateMKAverage","addElement","calculateMKAverage","addElement","addElement","addElement","calculateMKAverage"] [[3,1],[3],[1],[],[10],[],[5],[5],[5],[]]
find-median-from-data-stream)kth-largest-element-in-a-stream)sequentially-ordinal-rank-tracker)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1825: Finding MK Average
class MKAverage {
private int m, k;
private long s;
private int size1, size3;
private Deque<Integer> q = new ArrayDeque<>();
private TreeMap<Integer, Integer> lo = new TreeMap<>();
private TreeMap<Integer, Integer> mid = new TreeMap<>();
private TreeMap<Integer, Integer> hi = new TreeMap<>();
public MKAverage(int m, int k) {
this.m = m;
this.k = k;
}
public void addElement(int num) {
if (lo.isEmpty() || num <= lo.lastKey()) {
lo.merge(num, 1, Integer::sum);
++size1;
} else if (hi.isEmpty() || num >= hi.firstKey()) {
hi.merge(num, 1, Integer::sum);
++size3;
} else {
mid.merge(num, 1, Integer::sum);
s += num;
}
q.offer(num);
if (q.size() > m) {
int x = q.poll();
if (lo.containsKey(x)) {
if (lo.merge(x, -1, Integer::sum) == 0) {
lo.remove(x);
}
--size1;
} else if (hi.containsKey(x)) {
if (hi.merge(x, -1, Integer::sum) == 0) {
hi.remove(x);
}
--size3;
} else {
if (mid.merge(x, -1, Integer::sum) == 0) {
mid.remove(x);
}
s -= x;
}
}
for (; size1 > k; --size1) {
int x = lo.lastKey();
if (lo.merge(x, -1, Integer::sum) == 0) {
lo.remove(x);
}
mid.merge(x, 1, Integer::sum);
s += x;
}
for (; size3 > k; --size3) {
int x = hi.firstKey();
if (hi.merge(x, -1, Integer::sum) == 0) {
hi.remove(x);
}
mid.merge(x, 1, Integer::sum);
s += x;
}
for (; size1 < k && !mid.isEmpty(); ++size1) {
int x = mid.firstKey();
if (mid.merge(x, -1, Integer::sum) == 0) {
mid.remove(x);
}
s -= x;
lo.merge(x, 1, Integer::sum);
}
for (; size3 < k && !mid.isEmpty(); ++size3) {
int x = mid.lastKey();
if (mid.merge(x, -1, Integer::sum) == 0) {
mid.remove(x);
}
s -= x;
hi.merge(x, 1, Integer::sum);
}
}
public int calculateMKAverage() {
return q.size() < m ? -1 : (int) (s / (q.size() - k * 2));
}
}
/**
* Your MKAverage object will be instantiated and called as such:
* MKAverage obj = new MKAverage(m, k);
* obj.addElement(num);
* int param_2 = obj.calculateMKAverage();
*/
// Accepted solution for LeetCode #1825: Finding MK Average
type MKAverage struct {
lo, mid, hi *redblacktree.Tree
q []int
m, k, s int
size1, size3 int
}
func Constructor(m int, k int) MKAverage {
lo := redblacktree.NewWithIntComparator()
mid := redblacktree.NewWithIntComparator()
hi := redblacktree.NewWithIntComparator()
return MKAverage{lo, mid, hi, []int{}, m, k, 0, 0, 0}
}
func (this *MKAverage) AddElement(num int) {
merge := func(rbt *redblacktree.Tree, key, value int) {
if v, ok := rbt.Get(key); ok {
nxt := v.(int) + value
if nxt == 0 {
rbt.Remove(key)
} else {
rbt.Put(key, nxt)
}
} else {
rbt.Put(key, value)
}
}
if this.lo.Empty() || num <= this.lo.Right().Key.(int) {
merge(this.lo, num, 1)
this.size1++
} else if this.hi.Empty() || num >= this.hi.Left().Key.(int) {
merge(this.hi, num, 1)
this.size3++
} else {
merge(this.mid, num, 1)
this.s += num
}
this.q = append(this.q, num)
if len(this.q) > this.m {
x := this.q[0]
this.q = this.q[1:]
if _, ok := this.lo.Get(x); ok {
merge(this.lo, x, -1)
this.size1--
} else if _, ok := this.hi.Get(x); ok {
merge(this.hi, x, -1)
this.size3--
} else {
merge(this.mid, x, -1)
this.s -= x
}
}
for ; this.size1 > this.k; this.size1-- {
x := this.lo.Right().Key.(int)
merge(this.lo, x, -1)
merge(this.mid, x, 1)
this.s += x
}
for ; this.size3 > this.k; this.size3-- {
x := this.hi.Left().Key.(int)
merge(this.hi, x, -1)
merge(this.mid, x, 1)
this.s += x
}
for ; this.size1 < this.k && !this.mid.Empty(); this.size1++ {
x := this.mid.Left().Key.(int)
merge(this.mid, x, -1)
this.s -= x
merge(this.lo, x, 1)
}
for ; this.size3 < this.k && !this.mid.Empty(); this.size3++ {
x := this.mid.Right().Key.(int)
merge(this.mid, x, -1)
this.s -= x
merge(this.hi, x, 1)
}
}
func (this *MKAverage) CalculateMKAverage() int {
if len(this.q) < this.m {
return -1
}
return this.s / (this.m - 2*this.k)
}
/**
* Your MKAverage object will be instantiated and called as such:
* obj := Constructor(m, k);
* obj.AddElement(num);
* param_2 := obj.CalculateMKAverage();
*/
# Accepted solution for LeetCode #1825: Finding MK Average
class MKAverage:
def __init__(self, m: int, k: int):
self.m = m
self.k = k
self.s = 0
self.q = deque()
self.lo = SortedList()
self.mid = SortedList()
self.hi = SortedList()
def addElement(self, num: int) -> None:
if not self.lo or num <= self.lo[-1]:
self.lo.add(num)
elif not self.hi or num >= self.hi[0]:
self.hi.add(num)
else:
self.mid.add(num)
self.s += num
self.q.append(num)
if len(self.q) > self.m:
x = self.q.popleft()
if x in self.lo:
self.lo.remove(x)
elif x in self.hi:
self.hi.remove(x)
else:
self.mid.remove(x)
self.s -= x
while len(self.lo) > self.k:
x = self.lo.pop()
self.mid.add(x)
self.s += x
while len(self.hi) > self.k:
x = self.hi.pop(0)
self.mid.add(x)
self.s += x
while len(self.lo) < self.k and self.mid:
x = self.mid.pop(0)
self.lo.add(x)
self.s -= x
while len(self.hi) < self.k and self.mid:
x = self.mid.pop()
self.hi.add(x)
self.s -= x
def calculateMKAverage(self) -> int:
return -1 if len(self.q) < self.m else self.s // (self.m - 2 * self.k)
# Your MKAverage object will be instantiated and called as such:
# obj = MKAverage(m, k)
# obj.addElement(num)
# param_2 = obj.calculateMKAverage()
// Accepted solution for LeetCode #1825: Finding MK Average
/**
* [1825] Finding MK Average
*
* 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:
* <ol>
* If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.
* Remove the smallest k elements and the largest k elements from the container.
* Calculate the average value for the rest of the elements rounded down to the nearest integer.
* </ol>
* 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.
*
*
* 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^5
* 1 <= k*2 < m
* 1 <= num <= 10^5
* At most 10^5 calls will be made to addElement and calculateMKAverage.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/finding-mk-average/
// discuss: https://leetcode.com/problems/finding-mk-average/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Credit: https://leetcode.com/problems/finding-mk-average/solutions/3019890/rust-btreemap-vecdeque/
struct MKAverage {
m: usize,
k: usize,
m_sum: i32,
stream: std::collections::VecDeque<i32>,
sort: std::collections::BTreeMap<i32, i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MKAverage {
fn new(m: i32, k: i32) -> Self {
Self {
m: m as usize,
k: k as usize,
m_sum: 0,
stream: std::collections::VecDeque::new(),
sort: std::collections::BTreeMap::new(),
}
}
fn add_element(&mut self, num: i32) {
self.stream.push_back(num);
*self.sort.entry(num).or_insert(0) += 1;
self.m_sum += num;
if self.stream.len() > self.m {
let rem = self.stream.pop_front().unwrap();
*self.sort.get_mut(&rem).unwrap() -= 1;
if self.sort.get(&rem).unwrap() == &0 {
self.sort.remove(&rem);
}
self.m_sum -= rem;
}
}
fn calculate_mk_average(&self) -> i32 {
if self.stream.len() < self.m {
return -1;
}
let mut k_sum = 0;
let mut k_times = self.k;
'label: for (num, count) in self.sort.iter().take(self.k) {
for _ in 0..*count {
k_sum += num;
k_times -= 1;
if k_times < 1 {
break 'label;
}
}
}
k_times = self.k;
'label2: for (num, count) in self.sort.iter().rev().take(self.k) {
for _ in 0..*count {
k_sum += num;
k_times -= 1;
if k_times < 1 {
break 'label2;
}
}
}
// calc average
let sum = self.m_sum - k_sum as i32;
sum / (self.m - 2 * self.k) as i32
}
}
/**
* Your MKAverage object will be instantiated and called as such:
* let obj = MKAverage::new(m, k);
* obj.add_element(num);
* let ret_2: i32 = obj.calculate_mk_average();
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1825_example_1() {
let mut obj = MKAverage::new(3, 1);
obj.add_element(3); // current elements are [3]
obj.add_element(1); // current elements are [3,1]
assert_eq!(obj.calculate_mk_average(), -1); // return -1, because m = 3 and only 2 elements exist.
obj.add_element(10); // current elements are [3,1,10]
assert_eq!(obj.calculate_mk_average(), 3); // 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.add_element(5); // current elements are [3,1,10,5]
obj.add_element(5); // current elements are [3,1,10,5,5]
obj.add_element(5); // current elements are [3,1,10,5,5,5]
assert_eq!(obj.calculate_mk_average(), 5); // 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
}
}
// Accepted solution for LeetCode #1825: Finding MK Average
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1825: Finding MK Average
// class MKAverage {
//
// private int m, k;
// private long s;
// private int size1, size3;
// private Deque<Integer> q = new ArrayDeque<>();
// private TreeMap<Integer, Integer> lo = new TreeMap<>();
// private TreeMap<Integer, Integer> mid = new TreeMap<>();
// private TreeMap<Integer, Integer> hi = new TreeMap<>();
//
// public MKAverage(int m, int k) {
// this.m = m;
// this.k = k;
// }
//
// public void addElement(int num) {
// if (lo.isEmpty() || num <= lo.lastKey()) {
// lo.merge(num, 1, Integer::sum);
// ++size1;
// } else if (hi.isEmpty() || num >= hi.firstKey()) {
// hi.merge(num, 1, Integer::sum);
// ++size3;
// } else {
// mid.merge(num, 1, Integer::sum);
// s += num;
// }
// q.offer(num);
// if (q.size() > m) {
// int x = q.poll();
// if (lo.containsKey(x)) {
// if (lo.merge(x, -1, Integer::sum) == 0) {
// lo.remove(x);
// }
// --size1;
// } else if (hi.containsKey(x)) {
// if (hi.merge(x, -1, Integer::sum) == 0) {
// hi.remove(x);
// }
// --size3;
// } else {
// if (mid.merge(x, -1, Integer::sum) == 0) {
// mid.remove(x);
// }
// s -= x;
// }
// }
// for (; size1 > k; --size1) {
// int x = lo.lastKey();
// if (lo.merge(x, -1, Integer::sum) == 0) {
// lo.remove(x);
// }
// mid.merge(x, 1, Integer::sum);
// s += x;
// }
// for (; size3 > k; --size3) {
// int x = hi.firstKey();
// if (hi.merge(x, -1, Integer::sum) == 0) {
// hi.remove(x);
// }
// mid.merge(x, 1, Integer::sum);
// s += x;
// }
// for (; size1 < k && !mid.isEmpty(); ++size1) {
// int x = mid.firstKey();
// if (mid.merge(x, -1, Integer::sum) == 0) {
// mid.remove(x);
// }
// s -= x;
// lo.merge(x, 1, Integer::sum);
// }
// for (; size3 < k && !mid.isEmpty(); ++size3) {
// int x = mid.lastKey();
// if (mid.merge(x, -1, Integer::sum) == 0) {
// mid.remove(x);
// }
// s -= x;
// hi.merge(x, 1, Integer::sum);
// }
// }
//
// public int calculateMKAverage() {
// return q.size() < m ? -1 : (int) (s / (q.size() - k * 2));
// }
// }
//
// /**
// * Your MKAverage object will be instantiated and called as such:
// * MKAverage obj = new MKAverage(m, k);
// * obj.addElement(num);
// * int param_2 = obj.calculateMKAverage();
// */
Use this to step through a reusable interview workflow for this problem.
Use a simple list or array for storage. Each operation (get, put, remove) requires a linear scan to find the target element — O(n) per operation. Space is O(n) to store the data. The linear search makes this impractical for frequent operations.
Design problems target O(1) amortized per operation by combining data structures (hash map + doubly-linked list for LRU, stack + min-tracking for MinStack). Space is always at least O(n) to store the data. The challenge is achieving constant-time operations through clever structure composition.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.