Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Leetcode Reconstruct Itinerary problem solution

YASH PAL, 31 July 202421 January 2026

In this Leetcode Reconstruct Itinerary problem solution, 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 from at least one valid itinerary. You must use all the tickets once and only once.

Leetcode Reconstruct Itinerary problem solution

Leetcode Reconstruct Itinerary problem solution in Python.

class Solution(object):
    def findItinerary(self, tickets):
        
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        
        graph = collections.defaultdict(list)
        for x,y in tickets:
            graph[x].append(y)
        for city in graph:
            graph[city] = sorted(graph[city])
        ans = []
        stack = ['JFK']
        while stack:
            top = stack[-1]
            if not graph[top]:
                ans.append(top)
                stack.pop()
            else:
                stack.append(graph[top][0])
                del graph[top][0]
        return ans[::-1]

Problem solution in Java.

class Solution {
    Map<String, List<String>> graph;
    Map<String, boolean[]> visited;
    int totalC;
    public List<String> findItinerary(List<List<String>> tickets) {
        graph = new HashMap<>();
        visited = new HashMap<>();
        for(List<String> edges:tickets){
            if(graph.containsKey(edges.get(0))){
                graph.get(edges.get(0)).add(edges.get(1));
            }else{
                graph.put(edges.get(0), new ArrayList<>(Arrays.asList(edges.get(1))));
            }
        }
        this.totalC = tickets.size() + 1;
        for(String key : graph.keySet()){
            List<String> des = graph.get(key);
            Collections.sort(des);
            visited.put(key, new boolean[des.size()]);
        }        
        return dfs("JFK", 1);
    }
    
    List<String> dfs(String dest, int depth){
        if(depth == totalC){
            return new ArrayList<>(Arrays.asList(dest));
        }
        List<String> res = new ArrayList<>();
        List<String> children = graph.get(dest);
        if(children == null) return res;
        boolean[] nextState = visited.get(dest);
        for(int i = 0; i < children.size(); i++){
            // for each dest
            if(nextState[i]){
                continue;
            }
            visited.get(dest)[i] = true;
            List<String> validChild = dfs(children.get(i), depth + 1);
            if(validChild != null && validChild.size() > 0){
                validChild.add(0, dest);
                return validChild;
            }
            visited.get(dest)[i] = false;
        }
        return res;
    }
}

Reconstruct Itinerary problem solution in C++.

struct compare {
    bool operator() (string &a, string &b) {
        return (a>b);
    }
};

class Solution {
public:
  vector<string> findItinerary(vector<vector<string>>& tickets) {
    int n = tickets.size();
    string start = "JFK";
    for(auto t: tickets) {
        cities[t[0]].push(t[1]);
    }
    vector<string> v;
    dfs(start, v);
    return {v.rbegin(), v.rend()};
  }

  void dfs(string curr, vector<string> &v) {
    auto &pq = cities[curr];
    while(!pq.empty()) {
      string next = pq.top();
      pq.pop();
      dfs(next, v);
    }
    v.push_back(curr);
  }

private:
    unordered_map<string, priority_queue<string, vector<string>, compare>> cities;
};

coding problems solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes