Finding MK Average — LeetCode 1825 Python Solution
HardDesignQueueData StreamOrdered SetHeap (Priority Queue)
- Problem
- #1825
- Pattern
- Heap / Priority Queue
- Reading time
- 10 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
- Output
- [null, null, null, -1, null, 3, null, null, null, 5]
- Explanation
- MKAverage obj = new MKAverage(3, 1);
Python solution
Python
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()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(m) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1825. Finding MK Average is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1825. Finding MK Average?
- LeetCode 1825. Finding MK Average is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1825. Finding MK Average?
- The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 1825. Finding MK Average?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 1825. Finding MK Average cover?
- LeetCode 1825. Finding MK Average is tagged Design, Queue, Data Stream, Ordered Set and Heap (Priority Queue) on LeetCode.