36/40
Part 8 of 8 · Follow-upsLearn and do

The median across many machines: binary-search the value

Don't ship the data. Each machine sorts its own numbers once. Then binary-search the value, the way kth_by_search did in the worked example: lo and hi are values, and each round asks whether at least k numbers are at most mid.

  1. Send a candidate x to every machine.
  2. Each machine answers how many of its numbers are at most x. On a sorted list that's bisect.bisect_right(a, x), the first index whose item is greater than x.
  3. The sums say which half to keep: at least k, and hi = mid. Fewer, and lo = mid + 1.

Integer values below 2322^{32} take about 32 rounds, each with one small message per machine.

The mode is a counting question instead. Send each value to the machine that owns its hash, so all copies of a value meet in one place. Count there with a Counter from the hash-maps lesson, and compare each machine's top count.

In the editor, each machine holds a sorted list of numbers. Write kth_across(machines, k): binary-search the value, and let each machine count its numbers at most mid with bisect.bisect_right.