Try to solve the Reconstruct Itinerary problem.
Statement
Given a list of airline tickets
where tickets[i] = [from
i
, to
i
]
represent a departure airport and an arrival airport of a single flight, reconstruct the itinerary in the correct order and return it.
The person who owns these tickets
always starts their journey from "JFK"
. Therefore, the itinerary must begin with "JFK"
. If there are multiple valid itineraries, you should prioritize the one with the smallest
For example, the itinerary
["JFK", "EDU"]
has a smaller lexical order than["JFK", "EDX"]
.
Note: You may assume all tickets form at least one valid itinerary. You must use all the tickets exactly once.
Constraints:
tickets.length
tickets[i].length
from
i
.length
to
i
.length
from
i
to
i
from
i
andto
i
consist of uppercase English letters.
Example
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Reconstruct Itinerary
Given the following list of tickets
, what is the correct itinerary starting from “JFK”
?
tickets
[[“JFK”, “ABC”], [“ABC”, “COA”], [“JFK”, “ABX”], [“COA", "JFK”]]
[“JFK”, “ABC”, “COA”, “JFK”, “ABX”]
[“JFK”, “ABX”, “JFK”, “ABC”, “COA”, “JFK”]
[“JFK”, “ABC”, “JFK”, “COA”, “ABX”]
[“ABX”, “JFK”, “COA”, “JFK”, “ABC”]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;public class Solution {public static List<String> findItinerary(List<List<String>> tickets) {// Replace this placeholder return statement with your codereturn new ArrayList<>();}}