Amazon interview question

Solve Leetcode question (leetcode medium)