Amazon interview question

Leetcode medium-hard level question for the OA