Domanda di colloquio di Meta

Basic algorithmic question. Improve time and space complexity.