Round Trip II

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

Your task is to design a round trip that begins in a city, goes through one or more other cities, and finally returns to the starting city. Every intermediate city on the route must be strictly distinct.

Return an array containing the sequence of cities on the valid round trip (starting and ending with the same city). If there are multiple valid round trips, you may return any of them. If no such round trip exists, return an empty array [].

Example 1:

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

Output: [2, 1, 3, 2]

Explanation:

You can start at city 2, fly to 1, then to 3, and back to 2. Another valid answer would be [1, 3, 2, 1] or [3, 2, 1, 3].

Example 2:

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

Output: [ ]

Explanation:

All flights move forward (from lower to higher numbered cities). There is no way to return to any previously visited city.

Now Your Turn!

Pick the correct output for the given input

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

Still unsure what the problem is asking ?

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

Constraints:

  • 1 <= n <= 105
  • 1 <= flights.length <= 2*105
  • flights[i].length == 2
  • 1 <= from_city, to_city <= n
  • All connections are one-way flights.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

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

Input:

Flights
N