Amazon Interview Question

it was medium level leet code