Amazon interview question

Same as Leetcode coding problem.