TikTok interview question

Hackerrank question of high difficulty.