#1825

Finding MK Average

Hard
DesignQueueHeap (Priority Queue)Data StreamOrdered SetHash MapArraySliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(m)
O(m)
💡

Intuition

Time O(n log m)Space O(m)

The optimal approach uses a combination of a deque and a balanced binary search tree (or a sorted list) to efficiently maintain the last 'm' elements and quickly compute the MKAverage without needing to sort every time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a deque to store the last 'm' elements of the stream.
  2. 2Step 2: Maintain a sorted data structure (like a SortedList or a balanced BST) to keep track of the elements for quick access to the smallest and largest 'k' elements.
  3. 3Step 3: When calculating MKAverage, directly access the smallest and largest 'k' elements from the sorted structure and compute the average of the remaining elements.
solution.py22 lines
1from collections import deque
2import sortedcontainers
3
4class MKAverage:
5    def __init__(self, m: int, k: int):
6        self.m = m
7        self.k = k
8        self.stream = deque()
9        self.sorted_elements = sortedcontainers.SortedList()
10
11    def addElement(self, num: int) -> None:
12        self.stream.append(num)
13        self.sorted_elements.add(num)
14        if len(self.stream) > self.m:
15            removed = self.stream.popleft()
16            self.sorted_elements.remove(removed)
17
18    def calculateMKAverage(self) -> int:
19        if len(self.stream) < self.m:
20            return -1
21        relevant_elements = self.sorted_elements[self.k:self.m - self.k]
22        return sum(relevant_elements) // len(relevant_elements)

Complexity note: The time complexity is O(n log m) because each insertion and deletion in the sorted structure takes logarithmic time, and we do this for each element in the stream. The space complexity is O(m) due to storing the last 'm' elements.

  • 1Maintaining a sorted structure allows for efficient access to the smallest and largest elements.
  • 2Using a deque helps manage the stream of elements efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.