Amazon interview question

medium difficulty problem question and follow up