Approach
Breadth-first search
For Design an Array Statistics Tracker, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 51 lines of C++ from the credited upstream file 3369.cpp.
- The implementation visibly relies on hash lookup, work queue.
- 1 loop block detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class StatisticsTracker {2 public:3 void addNumber(int number) {4 q.push(number);5 ++count[number];6 sortedList.insert(number);7 modeMaxHeap.emplace(count[number], -number);8 sum += number;9 }10 11 void removeFirstAddedNumber() {12 const int number = q.front();13 q.pop();14 if (--count[number])15 count.erase(number);16 sortedList.erase(sortedList.find(number));17 18 19 sum -= number;20 }21 22 int getMean() {23 return sum / q.size();24 }25 26 int getMedian() {27 auto it = sortedList.begin();28 advance(it, sortedList.size() / 2);29 return *it;30 }31 32 int getMode() {33 34 while (!modeMaxHeap.empty()) {35 const int frequency = modeMaxHeap.top().first;36 const int number = -modeMaxHeap.top().second;37 if (count.contains(number) && count[number] == frequency)38 return number;39 modeMaxHeap.pop();40 }41 throw;42 }43 44 private:45 queue<int> q;46 unordered_map<int, int> count;47 multiset<int> sortedList;48 priority_queue<pair<int, int>> modeMaxHeap; 49 long sum = 0;50};51