Domanda di colloquio di Amazon

How would you implement the code with less time and space complexity?