Amazon interview question

Leetcode question with two parts