Amazon Interview Question

A puzzle which had to be solved using an algorithm and also write code for the same