Solving Leetcode Interviews in Seconds with AI: Reconstruct Itinerary
Introduction
In this blog post, we will explore how to solve the LeetCode problem "332" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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: Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"] Example 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
Explanation
- Hierholzer's Algorithm with Lexicographical Ordering: Use Hierholzer's algorithm to find an Eulerian path in the directed graph represented by the tickets. Prioritize destinations in lexicographical order to ensure the smallest lexical itinerary.
- Priority Queue for Destinations: Employ a priority queue (min-heap) to efficiently select the next destination with the smallest lexical order during the traversal.
- Backtracking to Build Itinerary: Build the itinerary by backtracking from the ending airport to the starting airport ("JFK").
- Runtime Complexity: O(E log V), where E is the number of tickets (edges) and V is the number of unique airports (vertices). The log V factor comes from the priority queue operations.
- Storage Complexity: O(E + V), mainly due to storing the graph (adjacency list) and the itinerary.
Code
import heapq
from collections import defaultdict
def findItinerary(tickets):
"""
Reconstructs the itinerary in order and returns it.
Args:
tickets: A list of airline tickets.
Returns:
A list representing the itinerary.
"""
graph = defaultdict(list)
for src, dest in tickets:
graph[src].append(dest)
for src in graph:
graph[src].sort()
itinerary = []
def dfs(airport):
while graph[airport]:
next_airport = graph[airport].pop(0)
dfs(next_airport)
itinerary.append(airport)
dfs("JFK")
return itinerary[::-1]