Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Reconstruct Itinerary problem solution

YASH PAL, 31 July 2024

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

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;
    }
}

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

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes