Amazon Lab126 interview question

leetcode medium level question and follow up