Amazon interview question

Medium to hard leetcode question