Skip to content

Commit 62f4929

Browse files
committed
Add problem 332 - Reconstruct Itinerary
1 parent d594040 commit 62f4929

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import heapq
2+
from collections import defaultdict, deque
3+
from typing import List
4+
5+
6+
class ReconstructItinerary:
7+
@staticmethod
8+
def findItinerary(tickets: List[List[str]]) -> List[str]:
9+
# Since we need to return the path in lexical order, we will
10+
# use minHeap to store airports. Thus, we need a map that will
11+
# connect the departure and arrival airports
12+
flights = defaultdict(list)
13+
# List to store the final path
14+
path = deque()
15+
# Process all flights to create the mappings
16+
for departure, arrival in tickets:
17+
heapq.heappush(flights[departure], arrival)
18+
19+
def dfs(departure_airport):
20+
while flights[departure_airport]:
21+
dfs(heapq.heappop(flights[departure_airport]))
22+
path.appendleft(departure_airport)
23+
24+
# We start from JFK, hence we will perform DFS from there
25+
dfs("JFK")
26+
return list(path)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import unittest
2+
3+
from problems.graph.reconstruct_itinerary import ReconstructItinerary
4+
5+
6+
class TestReconstructItinerary(unittest.TestCase):
7+
def test_find_itinerary(self):
8+
reconstruct_itinerary = ReconstructItinerary()
9+
10+
# Test case 1
11+
tickets1 = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
12+
expected1 = ["JFK", "MUC", "LHR", "SFO", "SJC"]
13+
self.assertEqual(reconstruct_itinerary.findItinerary(tickets1), expected1)
14+
15+
# Test case 2
16+
tickets2 = [["JFK", "SFO"], ["JFK", "ATL"], ["SFO", "ATL"], ["ATL", "JFK"], ["ATL", "SFO"]]
17+
expected2 = ["JFK", "ATL", "JFK", "SFO", "ATL", "SFO"]
18+
self.assertEqual(reconstruct_itinerary.findItinerary(tickets2), expected2)
19+
20+
21+
if __name__ == "__main__":
22+
unittest.main()

0 commit comments

Comments
 (0)