Pregunta de entrevista de Meta

2 algorithm question, the second one is harder.