Amazon Interview Question

leetcode looking question but slightly harder