Amazon Interview Question

Algorithm optimization question.