oneby7

Advanced Graphs Special edges and paths

487. Reconstruct Itinerary

Hard

You are given a list of airline tickets. Each ticket tickets[i] = [from, to] is one flight from the airport from to the airport to. Airports are written as codes of three capital letters, such as JFK.

All the tickets belong to one traveller, who starts at JFK and flies with every ticket exactly once. Return the airports of that trip in the order they are visited, starting with JFK. The list has one more airport than there are tickets.

The tickets may allow more than one such trip. Return the one that comes first in alphabetical order when the trips are compared airport by airport: at the first position where two trips differ, the one with the smaller airport code comes first.

The examples write each ticket as one string, its two codes separated by a space. Your function receives each ticket as a list of two strings, so "JFK SFO" arrives as ["JFK","SFO"].

Example 1

DELDXBJFKLHR

Input: tickets = ["JFK LHR", "LHR DEL", "DEL LHR", "LHR JFK", "JFK DXB", "DXB DEL"]

Output: ["JFK","DXB","DEL","LHR","JFK","LHR","DEL"]

Explanation: At LHR the traveller holds tickets to DEL and to JFK. Flying to DEL first would leave the tickets LHR → JFK and JFK → LHR unused, so the trip goes back to JFK first.

Example 2

AMSJFKSIN

Input: tickets = ["JFK AMS", "JFK SIN", "SIN JFK"]

Output: ["JFK","SIN","JFK","AMS"]

Explanation: AMS comes before SIN, but nobody holds a ticket out of AMS. Flying there first would strand the traveller with two tickets left.

Example 3

BOSJFK

Input: tickets = ["JFK BOS", "BOS JFK", "JFK BOS", "BOS JFK"]

Output: ["JFK","BOS","JFK","BOS","JFK"]

Explanation: Two tickets can be the same flight. Each one is used once, so the trip flies to BOS twice.

Check your understanding

Work out the answer for this input before you write any code.

tickets = ["JFK MEX", "MEX JFK", "JFK CDG"]

Constraints

  • 1 ≤ tickets.length ≤ 105
  • tickets[i].length == 2
  • Every airport code is 3 uppercase English letters.
  • tickets[i][0] != tickets[i][1]
  • At least one trip from JFK uses every ticket exactly once.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.