Exact Mode, Median and Balanced Sort Over Ten Message-Passing Nodes
Heaps, Sorting & SearchModel answerLast updated
Integers live on ten machines that can only exchange messages. Write per-node programs for the exact mode, the median and a balanced global sort while sending as little data as possible.
A very large set of integers is split across 10 machines numbered 0 to 9. Every machine runs the same program, knows its own id, and keeps its share of the data in RAM. The only communication primitives are:
send(dest, message): hands a message to machinedestand returns immediately.recv(): blocks until a message arrives, then returns(source, message).
Assume each machine's share fits in memory but the whole set does not fit on one machine, delivery is reliable (no loss, no duplicates), and local computation is cheap compared with network transfer.
Write the per-node program for each task. Every answer must be exact, and the objective is to send as little data as possible.
- Mode. Find the most frequent value overall. State your tie-break rule.
- Median. Find the median of all values. State which median you return when the total count is even.
- Sort. Redistribute the data so machine 0 holds the smallest values in sorted order, machine 1 the next block, and so on, with all machines holding roughly equal counts.
For each part, explain:
- the number of rounds and the volume of data sent,
- how you avoid deadlock and mixed-up messages,
- how you handle empty machines, duplicates and skewed data,
- where the final answer ends up.
State any assumptions you make, such as where results must land and the range of the values.
Hints
Hint 1
For the mode, a value's global count is only known in one place if every copy of that value is routed to the same machine. Choose that machine with a hash, and combine counts locally before sending anything.
Hint 2
For the median you do not need to move the data. Binary search on the value itself: broadcast a candidate x and have each machine reply with a single integer, the number of its elements <= x. Traffic then depends on the value range, not on N.
Hint 3
For the sort, take regular samples from locally sorted data, choose splitters from them, cut each sorted array at the splitters and send each piece to exactly one destination. Compare keys as (value, node, local index) so duplicates cannot overload one machine.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Shared building blocks
- Tagged messages. Every message is
(tag, body). A fast peer may already be in a later phase, so a helper buffers anything that does not match the phase being awaited. - No deadlock.
sendnever blocks, and every phase is "send to everyone, then collect a known number of messages". There are no circular waits. - Local work first. Aggregate or sort locally before sending anything.
from collections import Counter, defaultdict
from bisect import bisect_left, bisect_right
import heapq
P = 10
pending = defaultdict(list)
def collect(tag, n):
while len(pending[tag]) < n:
src, (t, body) = recv()
pending[t].append((src, body))
return pending.pop(tag)
Part 1: Mode
Approach (MapReduce shuffle).
- Each node builds a local
Counter. - Each
(value, count)pair is sent to ownermix(value) % 10, wheremixis a deterministic integer hash shared by all nodes (for example multiply by a large odd constant). - Each value now lives on exactly one owner, so the owner's merged count is the true global count.
- Each owner picks its best pair under the order "highest count, then smallest value" and sends it to node 0. Node 0 applies the same order to at most 10 candidates.
def mode(me, data):
out = [[] for _ in range(P)]
for v, c in Counter(data).items():
out[mix(v) % P].append((v, c))
for d in range(P):
send(d, ("shuf", out[d])) # send even empty lists: counts stay fixed
merged = Counter()
for _, pairs in collect("shuf", P):
for v, c in pairs:
merged[v] += c
best = min(merged.items(), key=lambda kv: (-kv[1], kv[0]), default=None)
send(0, ("best", best))
if me == 0:
cands = [b for _, b in collect("best", P) if b]
return min(cands, key=lambda kv: (-kv[1], kv[0]))
Cost. One shuffle round plus one gather round. Traffic is at most the number of distinct (node, value) pairs, which never exceeds N, plus 10 final candidates. With heavy repetition it collapses to a tiny fraction of N. If nearly every value is distinct, about N pairs move, and an exact answer inherently needs that. Only approximate heavy-hitter sketches avoid it.
Why hash instead of "everything to node 0". Merge work and inbound bandwidth are spread over 10 nodes rather than concentrated on one.
Part 2: Median
Approach. Do not move the data. Run a distributed binary search over the value range.
- Each node sorts once and sends
(count, min, max)to node 0, which learns N and the global range[lo, hi]. - The k-th smallest value is the smallest x with
count(<= x) >= k. Node 0 broadcasts a midpoint, each node replies withbisect_right(data, mid)(one integer), and node 0 sums the replies and halves the range. - After about
log2(hi - lo + 1)rounds (at most 32 or 64 for ints) the search ends.
Duplicates. Counting <= x and taking the smallest x that reaches rank k handles repeats correctly.
Even N. Return the mean of the k-th and (k+1)-th values with k = N // 2. Find x1 as the k-th value. If count(<= x1) > k, then x2 = x1. Otherwise one more round has each node return its smallest element greater than x1, and x2 is the minimum of the replies. For odd N use k = (N+1)//2 and return x1. (If the interviewer wants the lower median, skip the x2 step.)
Empty nodes. They report count 0, no min or max, and always answer 0 to count queries (None to "next" queries).
def answer(data, kind, x):
i = bisect_right(data, x)
return i if kind == "count" else (data[i] if i < len(data) else None)
def median(me, data):
data.sort()
stat = (len(data), data[:1], data[-1:])
if me != 0:
send(0, ("stat", stat))
r = 0
while True:
[(_, q)] = collect(("q", r), 1)
if q is None:
return
send(0, (("a", r), answer(data, *q)))
r += 1
stats = [stat] + [b for _, b in collect("stat", P - 1)]
n = sum(s[0] for s in stats)
lo = min(s[1][0] for s in stats if s[1])
hi = max(s[2][0] for s in stats if s[2])
r = 0
def ask(kind, x):
nonlocal r
for d in range(1, P):
send(d, (("q", r), (kind, x)))
rep = [answer(data, kind, x)] + [b for _, b in collect(("a", r), P - 1)]
r += 1
return rep
def kth(k):
a, b = lo, hi
while a < b:
m = (a + b) // 2
if sum(ask("count", m)) >= k: b = m
else: a = m + 1
return a
k = (n + 1) // 2 if n % 2 else n // 2
x1 = kth(k)
if n % 2 or sum(ask("count", x1)) > k:
res = x1 if n % 2 else x1 # x2 == x1 when even
else:
x2 = min(v for v in ask("next", x1) if v is not None)
res = (x1 + x2) / 2
for d in range(1, P):
send(d, (("q", r), None)) # termination signal
return res
Cost. About 32 rounds, each with 9 tiny requests and 9 tiny replies, so roughly 600 integers in total, independent of N. Shipping all data costs N values, and shipping a sample is only approximate with traffic that grows with accuracy. The price is latency, since rounds are sequential. Querying 8 to 16 pivots per round cuts the round count to a handful at the cost of slightly larger messages.
Part 3: Sort (sample sort)
- Local sort, O((N/P) log(N/P)).
- Sample. Each node picks P evenly spaced elements and sends them to node 0 as keys
(value, node, index). Because keys include node and index they are all distinct, so a heavily repeated value is split across several destinations instead of overloading one. - Splitters. Node 0 sorts the roughly 100 sample keys, takes 9 evenly spaced ones and broadcasts them.
- Cut and exchange. For splitter
(v, src, idx), letL = bisect_left(data, v)andR = bisect_right(data, v). The cut position isLifme > src,Rifme < src, andmax(L, min(R, idx))ifme == src. That yields 10 contiguous slices, and slice j goes to node j. - Merge. Each node receives 10 sorted runs and merges them with
heapq.merge, O((N/P) log P).
def cut(data, v, src, idx, me):
L, R = bisect_left(data, v), bisect_right(data, v)
return L if me > src else R if me < src else max(L, min(R, idx))
def sort_all(me, data): # assumes N > 0 overall
data.sort(); n = len(data)
send(0, ("samp", [(data[i*n//P], me, i*n//P) for i in range(P)] if n else []))
if me == 0:
allk = sorted(k for _, s in collect("samp", P) for k in s)
spl = [allk[len(allk) * i // P] for i in range(1, P)]
for d in range(P):
send(d, ("spl", spl))
[(_, spl)] = collect("spl", 1)
cuts = [0] + [cut(data, *s, me) for s in spl] + [n]
for d in range(P):
send(d, ("run", data[cuts[d]:cuts[d+1]]))
return list(heapq.merge(*[r for _, r in collect("run", P)]))
Balance. With regular sampling, no node receives more than about 2N/P elements, even with skew.
Cost. Each element moves at most once (about N values in total), plus about 100 sample keys and 9 splitters. The unavoidable minimum is close to N(1 - 1/P) when the data starts randomly placed, so this is near-optimal. It takes 3 rounds: sample, splitters, exchange.
Common mistakes
- Sending raw values for the mode instead of pre-aggregated
(value, count)pairs. - Using a non-deterministic or per-node hash, so copies of a value land on different owners.
- Finding the median by sorting samples, which is approximate, or by gathering everything on node 0.
- Mishandling even N or duplicates in the median (use
count(<= x), notcount(< x)). - Splitting by value only in the sort, so one repeated value overloads one node.
- Not tagging phases, so early messages from fast peers are consumed by the wrong step.