Question d’entretien chez TikTok

LC medium question. Time complexity was more than expected.