J.P. Morgan interview question

How to solve the coding problem.