Skip to content

Building a histogram from raw data

Question

Write code that turns a list of numbers into a histogram.

Short answer

Choose bins, then count in one pass. Fix the range [min⁡,max⁡][\min,\max] and number of bins mm (width ww), set up mm zero counters, and for each xx increment bin ⌊(x−min⁡)/w⌋\lfloor(x-\min)/w\rfloor, clamping the top edge into the last bin and handling out-of-range values. This is O(n)O(n) time and O(m)O(m) space; discuss bin-width choice and normalising counts to a density.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.7, p.158; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question