Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created November 2, 2019 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priyankvex/373843c204336a0100a9798e8c706e74 to your computer and use it in GitHub Desktop.
Save priyankvex/373843c204336a0100a9798e8c706e74 to your computer and use it in GitHub Desktop.
Complete the itinerary
from collections import defaultdict
class Solution(object):
def solve(self, trips):
# create a sorted adjacency list from the trips
graph = defaultdict(list)
for source, destination in trips:
graph[source].append(destination)
for source in graph.keys():
graph[source] = sorted(graph[source], reverse=True)
route = []
stack = ["J"]
while stack:
current_city = stack[-1]
while graph[current_city]:
current_city = graph[current_city].pop()
stack.append(current_city)
route.append(stack.pop())
route = list(reversed(route))
return route
if __name__ == "__main__":
trips = [
("J", "A"),
("A", "D"),
("A", "B"),
("B", "C"),
("C", "A"),
("C", "E"),
("E", "C")
]
ans = Solution().solve(trips)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment