Pregunta de entrevista de Meta

Solve this algorithm problem in an optimised way