Pergunta de entrevista da empresa Amazon

Two questions, based on Leetcode difficulty, the first one would be rated as Easy, the second one might be Hard, it's a variant of Leetcode's Medium with additional requirement.