Question d’entretien chez Amazon

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