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
- 58 lines of Java from the credited upstream file 3369.java.
- The implementation visibly relies on hash lookup, ordered lookup, work queue.
- 2 loop blocks 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 void addNumber(int number) {3 q.offer(number);4 count.merge(number, 1, Integer::sum);5 sortedList.merge(number, 1, Integer::sum);6 modeMaxHeap.offer(new Pair<>(count.get(number), number));7 sum += number;8 }9 10 public void removeFirstAddedNumber() {11 final int number = q.poll();12 count.merge(number, -1, Integer::sum);13 if (count.get(number) == 0)14 count.remove(number);15 sortedList.merge(number, -1, Integer::sum);16 if (sortedList.get(number) == 0)17 sortedList.remove(number);18 sum -= number;19 }20 21 public int getMean() {22 return (int) (sum / q.size());23 }24 25 public int getMedian() {26 final int midIndex = q.size() / 2; 27 int count = 0;28 for (Map.Entry<Integer, Integer> entry : sortedList.entrySet()) {29 count += entry.getValue();30 if (count > midIndex)31 return entry.getKey();32 }33 throw new IllegalArgumentException();34 }35 36 public int getMode() {37 38 while (!modeMaxHeap.isEmpty()) {39 final int frequency = modeMaxHeap.peek().getKey();40 final int number = modeMaxHeap.peek().getValue();41 if (count.containsKey(number) && count.get(number) == frequency)42 return number;43 modeMaxHeap.poll();44 }45 throw new IllegalArgumentException();46 }47 48 private Queue<Integer> q = new LinkedList<>();49 private Map<Integer, Integer> count = new HashMap<>();50 private TreeMap<Integer, Integer> sortedList = new TreeMap<>();51 52 private PriorityQueue<Pair<Integer, Integer>> modeMaxHeap =53 new PriorityQueue<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey)54 .reversed()55 .thenComparingInt(Pair<Integer, Integer>::getValue));56 private long sum = 0;57}58