Code rewrite for algorithm in book <<Top 10 Code Interview Problem>>