Amazon Interview Question

Leetcode question of hard difficulty