Design an Array Statistics Tracker Problem
Description
LeetCode Problem 3369.
Design a data structure that keeps track of the values in it and answers some queries regarding their mean, median, and mode.
Implement the StatisticsTracker class.
StatisticsTracker(): Initialize theStatisticsTrackerobject with an empty array.void addNumber(int number): Addnumberto the data structure.void removeFirstAddedNumber(): Remove the earliest added number from the data structure.int getMean(): Return the floored mean of the numbers in the data structure.int getMedian(): Return the median of the numbers in the data structure.int getMode(): Return the mode of the numbers in the data structure. If there are multiple modes, return the smallest one.
Note:
- The mean of an array is the sum of all the values divided by the number of values in the array.
- The median of an array is the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
- The mode of an array is the element that appears most often in the array.
Example 1:
Input:
["StatisticsTracker", "addNumber", "addNumber", "addNumber", "addNumber", "getMean", "getMedian", "getMode", "removeFirstAddedNumber", "getMode"]
[[], [4], [4], [2], [3], [], [], [], [], []]
Output:
[null, null, null, null, null, 3, 4, 4, null, 2]
Explanation
StatisticsTracker statisticsTracker = new StatisticsTracker();
statisticsTracker.addNumber(4); // The data structure now contains [4]
statisticsTracker.addNumber(4); // The data structure now contains [4, 4]
statisticsTracker.addNumber(2); // The data structure now contains [4, 4, 2]
statisticsTracker.addNumber(3); // The data structure now contains [4, 4, 2, 3]
statisticsTracker.getMean(); // return 3
statisticsTracker.getMedian(); // return 4
statisticsTracker.getMode(); // return 4
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [4, 2, 3]
statisticsTracker.getMode(); // return 2
Example 2:
Input:
["StatisticsTracker", "addNumber", "addNumber", "getMean", "removeFirstAddedNumber", "addNumber", "addNumber", "removeFirstAddedNumber", "getMedian", "addNumber", "getMode"]
[[], [9], [5], [], [], [5], [6], [], [], [8], []]
Output:
[null, null, null, 7, null, null, null, null, 6, null, 5]
Explanation
StatisticsTracker statisticsTracker = new StatisticsTracker();
statisticsTracker.addNumber(9); // The data structure now contains [9]
statisticsTracker.addNumber(5); // The data structure now contains [9, 5]
statisticsTracker.getMean(); // return 7
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5]
statisticsTracker.addNumber(5); // The data structure now contains [5, 5]
statisticsTracker.addNumber(6); // The data structure now contains [5, 5, 6]
statisticsTracker.removeFirstAddedNumber(); // The data structure now contains [5, 6]
statisticsTracker.getMedian(); // return 6
statisticsTracker.addNumber(8); // The data structure now contains [5, 6, 8]
statisticsTracker.getMode(); // return 5
Constraints:
1 <= number <= 10^9- At most,
10^5calls will be made toaddNumber,removeFirstAddedNumber,getMean,getMedian, andgetModein total. removeFirstAddedNumber,getMean,getMedian, andgetModewill be called only if there is at least one element in the data structure.
Solution
Approach: Queue + Hash Table + Ordered Structures
Keep the following:
- a queue of the added numbers, so the earliest one can be removed;
- the running sum, which gives the floored mean in
O(1); - a hash table with the count of every value;
- the numbers in sorted order, whose middle element (index
size / 2, the larger one when the size is even) is the median; - a priority queue of
(count, value)entries ordered by larger count first, then smaller value, for the mode.
addNumber inserts into the sorted structure, increments the count and pushes the new (count, value) pair. removeFirstAddedNumber takes the front of the queue, removes it from the sorted structure, decrements its count and pushes the new pair if the count is still positive. For getMode, discard heap entries at the top whose count no longer matches the hash table (lazy deletion); the top is then the mode.
In languages with a balanced ordered set (such as Python's SortedList) the sorted structure and the mode order can both be kept in sets with O(log n) updates. The code here uses a sorted array, which is simple and fast enough for 10^5 operations.
Complexity: addNumber and removeFirstAddedNumber take O(n) for the array shift (a very small constant) plus O(log n) for the heap, the queries take O(1) and amortised O(log n); space is O(n), where n is the number of stored values.
from bisect import bisect_left, insort
from collections import defaultdict, deque
from heapq import heappop, heappush
class StatisticsTracker:
def __init__(self):
self.q = deque()
self.s = 0
self.cnt = defaultdict(int)
self.sorted = []
self.heap = []
def addNumber(self, number: int) -> None:
self.q.append(number)
insort(self.sorted, number)
self.cnt[number] += 1
heappush(self.heap, (-self.cnt[number], number))
self.s += number
def removeFirstAddedNumber(self) -> None:
number = self.q.popleft()
del self.sorted[bisect_left(self.sorted, number)]
self.cnt[number] -= 1
if self.cnt[number] > 0:
heappush(self.heap, (-self.cnt[number], number))
self.s -= number
def getMean(self) -> int:
return self.s // len(self.q)
def getMedian(self) -> int:
return self.sorted[len(self.q) // 2]
def getMode(self) -> int:
while -self.heap[0][0] != self.cnt[self.heap[0][1]]:
heappop(self.heap)
return self.heap[0][1]