Pergunta de entrevista da empresa Reddit

Leetcode question, followed by "what is the runtime/space complexity" and "how would you optimize this?"