Amazon interview question

Tricky but manageable with leetcode