Longest Flight Route

You are given n cities numbered from 1 to n. You are also given an array of one-way flights where flights[i] = [from_city, to_city].

You want to fly from city 1 to city n such that you visit the maximum possible number of cities along the way. It is guaranteed that there are no directed cycles in the flight network (the graph is a Directed Acyclic Graph).

Return an array containing the sequence of cities on the longest valid flight route from city 1 to city n. If there are multiple valid routes that visit the maximum number of cities, you may return any of them. If no such route exists, return an empty array [].

Example 1:

Input: n = 5, flights = [[1, 2], [2, 5], [1, 3], [3, 4], [4, 5]]

Output: [1, 3, 4, 5]

Explanation:

The valid paths from city 1 to city 5 are [1, 2, 5] (visiting 3 cities) and [1, 3, 4, 5] (visiting 4 cities). The longest path has 4 cities.

Example 2:

Input: n = 3, flights = [[1, 2]]

Output: [ ]

Explanation:

There is no flight connecting to city 3, so it is impossible to reach the destination from city 1.

Now Your Turn!

Pick the correct output for the given input

Input: n = 4, flights = [[1, 2], [2, 3], [3, 4], [1, 4]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n <= 105
  • 1 <= flights.length <= 2* 105
  • flights[i].length == 2
  • 1 <= from_city, to_city <= n
  • The flight network contains no directed cycles.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> longestFlightRoute(int n, vector<vector<int>>& flights) {
// Write your code here
}
};
Test Case

Input:

Flights
N