Amazon Interview Question

Leetcode hard question, on hacker rank