Microsoft Interview Question

They asked to solve the problem on paper (code), and than to optimize the solution i came u with.