Amazon interview question

a medium difficulty leetcode question