Amazon interview question

Leetcode easy to medium problem