Amazon Interview Question

The code question is leetcode 136