KatInterview

Exact Mode, Median and Balanced Sort Over Ten Message-Passing Nodes

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchdistributed-systemsmapreducesample-sort

Last 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 machine dest and 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.

  1. Mode. Find the most frequent value overall. State your tie-break rule.
  2. Median. Find the median of all values. State which median you return when the total count is even.
  3. 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.