My solution to a University of Waterloo Programming Competition question from 2009.