Pergunta de entrevista da empresa TikTok

Hackerrank question of high difficulty.