Pregunta de entrevista de Amazon

Leetcode question, at least between medium and hard.