Pergunta de entrevista da empresa Apple

Graph traversal question with optimization follow up