Post

LC 332 - Reconstruct Itinerary

LC 332 - Reconstruct Itinerary

Question

You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

  • For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

Example 1:

1
2
Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]

Example 2:

1
2
Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] **Explanation:** Another possible reconstruction is `["JFK","SFO","ATL","JFK","ATL","SFO"]` but it is larger in lexical order.

Constraints:

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • fromi.length == 3
  • toi.length == 3
  • fromi and toi consist of uppercase English letters.
  • fromi != toi

Question here and solution here

Solution

concept

The main idea is to construct a adjacency list but we have to sort the list such that DFS can be performed in the lexical order, this will make sure that the answer is correct.

code

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution:
	"""
	this solution is currently TLE
	use the modified version below
	"""
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        adj_list = defaultdict(list)
        for src, dst in tickets:
            adj_list[src].append(dst)
        # sort value only such that dfs will go according to lexical order
        for k,v in adj_list.items():
            v.sort()

        ans = ["JFK"]

        def dfs(node):
            if len(ans) == len(tickets) + 1:
                return True
            if node not in adj_list:
                return False
            # if not adj_list[node]:
            #     return False
            
            tmp = adj_list[node].copy()
            for i, v in enumerate(tmp):
                ans.append(v)
                adj_list[node].pop(i)
                if dfs(v):
                    return True
                ans.pop()
                adj_list[node].insert(i, v)

            return False

        dfs("JFK")
        return ans
        
class Solution:
    def dfs(self, src):
        if src in self.adj:
            # clone all the destination from that src
            destinations = self.adj[src][:]
            while destinations:
                dest = destinations[0]
                self.adj[src].pop(0)
                self.dfs(dest)
                destinations = self.adj[src][:]

        self.result.append(src)
        
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        # adjacency list {source : [destination]}
        self.adj = {src: [] for src, dst in tickets}
        self.result = []
        # populate adjaency list
        for src, dst in tickets:
            self.adj[src].append(dst)
        # sort destinations -> we need to search by lexical order
        for key in self.adj:
            self.adj[key].sort()
        
        self.dfs("JFK")
        self.result.reverse()

        if len(self.result) != len(tickets) + 1:
            return []
        return self.result

Complexity

time: $O(EV)$
space: $O(EV)$

This post is licensed under CC BY 4.0 by the author.