Mean, median and mode across many machines

55 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Combine each machine's summary into an exact mean and variance, and say why the mean of means is wrong
  • Merge variances without the sum-of-squares formula that loses precision
  • Find the overall mode by merging counts, and say why each machine's own mode isn't enough
  • Find an exact median across machines with a few rounds of count questions
  • Choose a heavy hitters summary or a quantile sketch when exact answers cost too much

Statistics across many nodes, the way the coding round asks

Anthropic coding rounds asked candidates for the mode and the median of data that sits on many nodes, through a messaging interface they were given (2 sources). This lesson's practice problem builds the whole answer, in three levels:

  1. summarize(values), merge(a, b) and mean_and_variance(summaries): each node sends its count, mean and spread, and the coordinator merges them into the exact mean and variance.
  2. global_mode(nodes): the most common value across every node, and the smallest one on a tie.
  3. distributed_median(nodes): the exact lower median, when each node only answers how many of its values are at or below v. The budget is about 12 rounds of questions.
CallReturns
merge((3, 10.0, 2.0), (1, 14.0, 0.0))(4, 11.0, 14.0)
mean_and_variance of the same two(11.0, 4.667)
global_mode([[3, 3, 5], [5, 7]])3: 3 and 5 tie at two each, and the smaller wins
distributed_median with nodes holding 5, 1, 9 and 3, 7, 23, the lower of the middle two

The lesson follows the shop's orders on 10 servers: merged means and variances, the mode, an exact median from count questions, and sketches for when exact costs too much. Six steps end with a small task in the editor.

Part 1 of 7about 7 min
The mean

Merge summaries, not answers

The shop has the same setup as the question: 10 servers, each holding its own region's orders, 1,000 orders in all. Start with the mean.

Predict

Each server reports the mean of its own orders. Is the average of the 10 means the mean of all 1,000 orders?

Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 15 min
The variance

Merge each server's count, mean and spread

For the variance, each server sends three numbers: its count n, its mean, and M2, the sum of squared distances from its own mean.

Predict

One server's orders are all $20 and another's are all $80, so each M2 is 0. Is the merged M2 also 0?

Pick an answer above to see the rest

Why not just send the sum of squares?

Each server could send its count, sum and sum of squares, and the coordinator could use Σx² − (Σx)²/n. Chan, Golub and LeVeque warned that computing a variance can be difficult when N is large and the variance is small. Try order timestamps:

Predict

1,000 order times in milliseconds sit near 1.76 trillion and spread over one second. What does Σx² − (Σx)²/n give for the variance?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 8 min
The mode

The best seller across all servers

The mode is next: the shop's best seller across all 10 servers.

Predict

Each server reports its best-selling product. Is the most common of those the best seller overall?

Pick an answer above to see the rest
Predict

After the shuffle by hash(product), what does each owner need to send the coordinator?

Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 10 min
The median

Find the median with count questions, not data

The median is the hard one.

Predict

Each server reports its median. Is the median of the 10 medians the median of all 1,000 orders?

Pick an answer above to see the rest
Predict

Orders run from $14 to $590. About how many rounds of questions does the search need?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 9 min
At scale

When exact costs too much, merge sketches

Count maps break down with a billion distinct products. A heavy hitters summary keeps only k counters. In the Misra-Gries version, a new item takes a free counter. When none is free, every counter drops by one, and the new item isn't stored: it spends itself cancelling one count from each. Two of these summaries merge by adding up the corresponding counters, then trimming back to k. Apache DataSketches' frequent items sketch returns, for any item, upper and lower bounds that always contain its true count, and BigQuery's APPROX_TOP_COUNT returns the approximate top elements.

Predict

A Misra-Gries summary keeps 2 counters over 14 orders. Which products are sure to survive?

Pick an answer above to see the rest

Quantile sketches

For medians and percentiles, Greenwald and Khanna defined an ε-approximate quantile summary: one that answers any quantile within εN ranks. Karnin, Lang and Liberty's KLL sketch is mergeable, a property they call extremely important because large datasets are often distributed across many machines. DataSketches' KLL default of K = 200 gives about 1.65% rank error. The t-digest is built to be most accurate near the tails, and Dunning and Ertl note that t-digests from disjoint partitions can be formed independently and then combined, which makes parallel processing simple.

Predict

A sketch promises 1% rank error. For the median of a billion orders, how far off can the answer's rank be?

Pick an answer above to see the rest
Predict

You store each day's median order value. Can 30 daily medians give the month's median?

Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 3 min
The worked example

A worked example: mode and median across nodes, out loud

Here's the Anthropic question, worked out loud.

Compute the mode and the median of data spread across many nodes, with a messaging interface. (2 sources)

1. Ask about sizes and costs. How many nodes and values? Integers or floats, and what range? Is a message expensive, or a round of messages?

Predict

There are 10 nodes and 1,000 values in all. What's the cheapest exact median?

Pick an answer above to see the rest
Predict

The values are floats, not integers. What goes wrong with binary search on the value?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 3 min
Follow-ups

A stream instead of a fixed set

Two follow-ups come up after this question. The first: the orders never stop.

Predict

Orders keep arriving. How does each node keep its (count, mean, M2) current without storing every order?

Pick an answer above to see the rest

Percentiles of latency

The second follow-up is the p99, the value 99% of requests come in under. The same tools give it. An exact p99 is a count search for the value at rank 0.99 N. A sketch built to be accurate near the tails, like the t-digest, is the usual choice when the p99 is watched all day.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.Ten servers report their mean order values. Why is the average of those means usually wrong?

  2. 2.What does the δ² × na × nb / n term add when two variance summaries merge?

  3. 3.Each server's best seller is a different product. Can the overall best seller be none of them?

  4. 4.The exact median search asks each server how many values are at or below v. What makes it fast?

  5. 5.A quantile sketch promises 1% error on a billion values. What is promised?

Practice

Sources (22)
  1. Mergeable Summaries · Agarwal, Cormode, Huang, Phillips, Wei and Yi, PODS 2012 · Mar 30, 2012
    “Informally speaking, mergeability requires that, given two summaries on two data sets, there is a way to merge the two summaries into a single summary on the union of the two data sets, while preserving the error and size guarantees.”
  2. MapReduce: Simplified Data Processing on Large Clusters · Dean and Ghemawat, OSDI 2004 · Dec 6, 2004
    “We allow the user to specify an optional Combiner function that does partial merging of this data before it is sent over the network.”
  3. Algorithms for Computing the Sample Variance: Analysis and Recommendations · Chan, Golub and LeVeque, The American Statistician (JSTOR abstract page) · Aug 1, 1983
    “The problem of computing the variance of a sample of N data points ... may be difficult for certain data sets, particularly when N is large and the variance is small.”
  4. Accurately computing sample variance online · John D. Cook · Nov 1, 2014
    “The loss of precision can be so bad that the expression above evaluates to a negative number even though variance is always positive.”
  5. pairwise algorithm for computing sample variances · Praat manual (Boersma and Weenink, University of Amsterdam), citing Chan, Golub and LeVeque 1979 · Aug 6, 2017
    “By pairwise combining array elements, the total number of arithmetic operations is reduced and therefore also the noise due to finite precision arithmetic.”
  6. Accurately computing sample variance online · John D. Cook · Nov 1, 2014
    “This better way of computing variance goes back to a 1962 paper by B. P. Welford”
  7. statistics: Mathematical statistics functions · Python documentation · Nov 19, 2026
    “If there are multiple modes with the same frequency, returns the first one encountered in the data.”
  8. MapReduce: Simplified Data Processing on Large Clusters · Dean and Ghemawat, OSDI 2004 · Dec 6, 2004
    “Reduce invocations are distributed by partitioning the intermediate key space into R pieces using a partitioning function (e.g., hash(key) mod R).”
  9. statistics: Mathematical statistics functions · Python documentation · Nov 19, 2026
    “When the number of data points is even, the median is interpolated by taking the average of the two middle values”
  10. Communication Efficient Algorithms for Top-k Selection Problems · Hübschle-Schneider, Sanders and Müller, arXiv 1502.03942 · Oct 19, 2015
    “This algorithm, FR-select, can be adapted to a distributed memory parallel setting”
  11. Mergeable Summaries · Agarwal, Cormode, Huang, Phillips, Wei and Yi, PODS 2012 · Mar 30, 2012
    “We first combine the two summaries by adding up the corresponding counters.”
  12. Frequent Items Overview · Apache DataSketches · Nov 19, 2026
    “Return upper and lower bounds of any item, such that the true frequency is always between the upper and lower bounds.”
  13. Approximate aggregate functions · Google Cloud BigQuery documentation · Nov 19, 2026
    “Returns the approximate top elements of expression as an array of STRUCTs.”
  14. Space-Efficient Online Computation of Quantile Summaries · Greenwald and Khanna, SIGMOD 2001 (copy hosted by Emory CS 584) · May 21, 2001
    “An ε-approximate quantile summary of a sequence of N elements is a data structure that can answer quantile queries about the sequence to within a precision of εN.”
  15. Optimal Quantile Approximation in Streams · Karnin, Lang and Liberty, arXiv 1603.05346 · Apr 5, 2016
    “This property is extremely important in practice since large datasets are often distributed across many machines.”
  16. KLL Sketch · Apache DataSketches · Nov 19, 2026
    “The default K of 200 was chosen to yield approximately the same normalized rank error (1.65%) as the classic quantiles DoublesSketch (K=128, error 1.73%).”
  17. Computing Extremely Accurate Quantiles Using t-Digests · Dunning and Ertl, arXiv 1902.04023 · Feb 11, 2019
    “We present on-line algorithms for computing approximations of rank-based statistics that give high accuracy, particularly near the tails of a distribution, with very small sketches.”
  18. Computing Extremely Accurate Quantiles Using t-Digests · Dunning and Ertl, arXiv 1902.04023 · Feb 11, 2019
    “The ability to merge t-digests makes parallel processing of large data-sets relatively simple since independent t-digests can be formed from disjoint partitions of the input data and then combined”
  19. pyspark.sql.DataFrame.approxQuantile · Apache Spark documentation · Nov 19, 2026
    “This method implements a variation of the Greenwald-Khanna algorithm (with some speed optimizations).”
  20. pyspark.sql.functions.percentile_approx · Apache Spark documentation · Nov 19, 2026
    “Higher value of accuracy yields better accuracy, 1.0/accuracy is the relative error of the approximation. (default: 10000).”
  21. Approximate aggregate functions · Google Cloud BigQuery documentation · Nov 19, 2026
    “Approximate aggregate functions are scalable in terms of time and resource usage, but produce approximate results instead of exact results.”
  22. KLL quantile functions · Google Cloud BigQuery documentation · Nov 19, 2026
    “While APPROX_QUANTILES is also returning approximate quantile results, the functions from this section allow for partial aggregations and re-aggregations.”