Amazon Interview Question

Leetcode question with two parts