Amazon interview question

Leetcode style problem