Amazon interview question

The code question is leetcode 136