Domanda di colloquio di TikTok

LC medium question. Time complexity was more than expected.