Amazon interview question

Leetcode hard question, on hacker rank