Pergunta de entrevista da empresa OfferUp

Leetcode question but it is a hard one.