Amazon interview question

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