Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
All Routes From Origin to Destination
00:00
5 left

All Routes From Origin to Destination

MediumPython

Problem

Hopper's flight search needs to display every possible itinerary between two airports using available directed flight legs. Given a set of flight connections, return all routes from an origin to a destination without visiting any airport more than once.

Formal Specification

Implement find_flight_routes(flights, origin, destination), where flights is a list of two-element lists [from_airport, to_airport]. Each connection is directed. Return a list of routes, where each route is a list of airport codes beginning with origin and ending with destination.

Return routes in the depth-first traversal order induced by the input connection order. If origin == destination, return a route containing only that airport. You may assume there are no duplicate connections. Routes must not contain cycles.

Example 1:

Input: flights = [["YUL", "YYZ"], ["YUL", "BOS"], ["YYZ", "LAX"], ["BOS", "LAX"]], origin = "YUL", destination = "LAX"
Output: [["YUL", "YYZ", "LAX"], ["YUL", "BOS", "LAX"]]

Both one-stop itineraries connect YUL to LAX.

Example 2:

Input: flights = [["YUL", "YYZ"], ["YYZ", "YUL"], ["YYZ", "LAX"]], origin = "YUL", destination = "LAX"
Output: [["YUL", "YYZ", "LAX"]]

The YUL to YYZ to YUL cycle is excluded.

Constraints

  • 0 <= len(flights) <= 10^4
  • Airport codes are non-empty strings
  • Each connection contains exactly two airport codes
  • There are no duplicate directed connections
  • The number of valid routes is manageable for the returned output
  • A route cannot visit an airport more than once

Function Signature

def find_flight_routes(flights, origin, destination):
Interviewer

Your question is All Routes From Origin to Destination. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.