Morgan Stanley interview question

solve this problem in python