Amazon Interview Question

medium difficulty problem question and follow up