Pergunta de entrevista da empresa IBM

Magic Carpet question that was easy Leetcode question.