Pergunta de entrevista da empresa Meta

2 algorithm question, the second one is harder.