Amazon interview question

Leetcode question, at least between medium and hard.