Design an Array Statistics Tracker - Problem
Design an Array Statistics Tracker
You need to design a smart data structure that can dynamically track statistical measures of numbers as they are added and removed. Think of it as a real-time analytics system that maintains running statistics!
Your StatisticsTracker class should support:
- Adding numbers: Insert new values into the tracker
- Removing numbers: Remove the earliest added number (FIFO - First In, First Out)
- Computing statistics: Calculate mean, median, and mode on-demand
Statistical Definitions:
- Mean: Sum of all values ÷ count of values (floored to integer)
- Median: Middle value when sorted. If even count, take the larger of the two middle values
- Mode: Most frequently occurring value. If multiple modes exist, return the smallest one
The challenge is to efficiently maintain these statistics as the data changes dynamically through additions and removals.
Input & Output
example_1.py — Basic Operations
$
Input:
["StatisticsTracker", "addNumber", "addNumber", "addNumber", "getMean", "getMedian", "getMode"]
[[], [1], [3], [1], [], [], []]
›
Output:
[null, null, null, null, 1, 1, 1]
💡 Note:
Initialize tracker, add 1, 3, 1. Mean = (1+3+1)/3 = 1, Median of [1,1,3] = 1 (middle), Mode = 1 (appears twice)
example_2.py — With Removal
$
Input:
["StatisticsTracker", "addNumber", "addNumber", "addNumber", "removeFirstAddedNumber", "getMean", "getMedian", "getMode"]
[[], [4], [2], [1], [], [], [], []]
›
Output:
[null, null, null, null, null, 1, 2, 1]
💡 Note:
Add 4,2,1 then remove first (4). Remaining: [2,1]. Mean = (2+1)/2 = 1, Median of [1,2] = 2 (larger middle), Mode = 1 (lexically smaller)
example_3.py — Edge Case Single Element
$
Input:
["StatisticsTracker", "addNumber", "getMean", "getMedian", "getMode", "removeFirstAddedNumber"]
›
Output:
[null, null, 5, 5, 5, null]
💡 Note:
Single element case: all statistics equal the element (5). After removal, tracker becomes empty.
Constraints
- 1 ≤ number ≤ 105
- At most 104 calls to addNumber and removeFirstAddedNumber
- At most 104 calls to getMean, getMedian, and getMode
- removeFirstAddedNumber is called only when the array is non-empty
- Statistics methods are called only when the array is non-empty
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code