Skip to main content
Back to problems
#332
Hard Algorithms

Reconstruct itinerary

Array String Depth-First Search Graph Theory Sorting Heap (Priority Queue) Eulerian Circuit
44.3% acceptance
Jan 12, 2026
6305
1926
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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_itinerary(tickets: Vec<Vec<String>>) -> Vec<String> {
    use std::collections::{HashMap, BinaryHeap};
    use std::cmp::Reverse;
    
    let mut graph: HashMap<String, BinaryHeap<Reverse<String>>> = HashMap::new();
    
    for ticket in tickets {
      graph.entry(ticket[0].clone())
        .or_insert_with(BinaryHeap::new)
        .push(Reverse(ticket[1].clone()));
    }
    
    let mut result = Vec::new();
    let mut stack = vec!["JFK".to_string()];
    
    while let Some(curr) = stack.last() {
      if let Some(dests) = graph.get_mut(curr) {
        if let Some(Reverse(next)) = dests.pop() {
          stack.push(next);
          continue;
        }
      }
      result.push(stack.pop().unwrap());
    }
    
    result.reverse();
    result
  }
}