-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0332-reconstruct-itinerary.js
More file actions
32 lines (27 loc) · 983 Bytes
/
0332-reconstruct-itinerary.js
File metadata and controls
32 lines (27 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Reconstruct Itinerary
* Time Complexity: O(E log E)
* Space Complexity: O(V + E)
*/
var findItinerary = function (tickets) {
const flightAdjacency = new Map();
const tourPath = [];
for (const [departurePoint, arrivalPoint] of tickets) {
if (!flightAdjacency.has(departurePoint)) {
flightAdjacency.set(departurePoint, []);
}
flightAdjacency.get(departurePoint).push(arrivalPoint);
}
for (const airportDests of flightAdjacency.values()) {
airportDests.sort((airportX, airportY) => airportY.localeCompare(airportX));
}
const depthFirstSearch = (currentNode) => {
while (flightAdjacency.has(currentNode) && flightAdjacency.get(currentNode).length > 0) {
const nextDestination = flightAdjacency.get(currentNode).pop();
depthFirstSearch(nextDestination);
}
tourPath.push(currentNode);
};
depthFirstSearch('JFK');
return tourPath.reverse();
};