Pergunta de entrevista da empresa Deem

Very complex augorithm question