Pergunta de entrevista da empresa Amazon

Leetcode question of hard difficulty