Pregunta de entrevista de Bloomberg

a medium leetcode question and a hard one