Amazon Interview Question

a medium difficulty leetcode question