Problem 6 of the September 2014 Microsoft Coding Competition