Domanda di colloquio di Meta

Solve this algorithm problem in an optimised way