Pregunta de entrevista de Amazon

graphs question.time complexity of the approach,optimal solution