Amazon Interview Question

Leetcode level problem very difficult