Pergunta de entrevista da empresa TikTok

Leetcode question. Then try to improve time complexity.