Amazon interview question

Leetcode level problem very difficult