Pregunta de entrevista de Amazon

Leetcode-style algorithm question. Was about medium difficulty.