Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
["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 <= 300tickets[i].length == 2fromi.length == 3toi.length == 3fromi and toi consist of uppercase English letters.fromi != toiProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
longest-common-subpath)valid-arrangement-of-pairs)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #332: Reconstruct Itinerary
class Solution {
private Map<String, List<String>> g = new HashMap<>();
private List<String> ans = new ArrayList<>();
public List<String> findItinerary(List<List<String>> tickets) {
Collections.sort(tickets, (a, b) -> b.get(1).compareTo(a.get(1)));
for (List<String> ticket : tickets) {
g.computeIfAbsent(ticket.get(0), k -> new ArrayList<>()).add(ticket.get(1));
}
dfs("JFK");
Collections.reverse(ans);
return ans;
}
private void dfs(String f) {
while (g.containsKey(f) && !g.get(f).isEmpty()) {
String t = g.get(f).remove(g.get(f).size() - 1);
dfs(t);
}
ans.add(f);
}
}
// Accepted solution for LeetCode #332: Reconstruct Itinerary
func findItinerary(tickets [][]string) (ans []string) {
sort.Slice(tickets, func(i, j int) bool {
return tickets[i][0] > tickets[j][0] || (tickets[i][0] == tickets[j][0] && tickets[i][1] > tickets[j][1])
})
g := make(map[string][]string)
for _, ticket := range tickets {
g[ticket[0]] = append(g[ticket[0]], ticket[1])
}
var dfs func(f string)
dfs = func(f string) {
for len(g[f]) > 0 {
t := g[f][len(g[f])-1]
g[f] = g[f][:len(g[f])-1]
dfs(t)
}
ans = append(ans, f)
}
dfs("JFK")
for i := 0; i < len(ans)/2; i++ {
ans[i], ans[len(ans)-1-i] = ans[len(ans)-1-i], ans[i]
}
return
}
# Accepted solution for LeetCode #332: Reconstruct Itinerary
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
def dfs(f: str):
while g[f]:
dfs(g[f].pop())
ans.append(f)
g = defaultdict(list)
for f, t in sorted(tickets, reverse=True):
g[f].append(t)
ans = []
dfs("JFK")
return ans[::-1]
// Accepted solution for LeetCode #332: Reconstruct Itinerary
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap};
impl Solution {
pub fn find_itinerary(tickets: Vec<Vec<String>>) -> Vec<String> {
let mut graph: HashMap<&str, BinaryHeap<Reverse<&str>>> = HashMap::new();
for ticket in tickets.iter() {
graph
.entry(&ticket[0])
.or_insert_with(BinaryHeap::new)
.push(Reverse(&ticket[1]));
}
let mut answer: Vec<String> = Vec::with_capacity(tickets.len() + 1);
let mut stack: Vec<&str> = vec!["JFK"];
while let Some(src) = stack.last() {
if let Some(dsts) = graph.get_mut(src) {
if !dsts.is_empty() {
if let Some(dst) = dsts.pop() {
stack.push(dst.0);
}
continue;
}
}
if let Some(last) = stack.pop() {
answer.push(last.to_string());
}
}
answer.reverse();
answer
}
}
// Accepted solution for LeetCode #332: Reconstruct Itinerary
function findItinerary(tickets: string[][]): string[] {
const g: Record<string, string[]> = {};
tickets.sort((a, b) => b[1].localeCompare(a[1]));
for (const [f, t] of tickets) {
g[f] = g[f] || [];
g[f].push(t);
}
const ans: string[] = [];
const dfs = (f: string) => {
while (g[f] && g[f].length) {
const t = g[f].pop()!;
dfs(t);
}
ans.push(f);
};
dfs('JFK');
return ans.reverse();
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.