Pergunta de entrevista da empresa Bloomberg

a medium leetcode question and a hard one