This question evaluates understanding of graph traversal and shortest-path concepts, particularly handling multiple mode-restricted subgraphs and multi-criteria comparison of path metrics (time and cost) across modes.
You are designing a route planner that suggests the best way to commute between two points in a city using different transportation modes.
The city is represented as an undirected graph with N intersections labeled 0 .. N-1 and M roads. There are K possible commute modes (e.g., walk, bike, drive) labeled 0 .. K-1.
Each road is described as:
u, v
— the two endpoints of the road (0-based node indices)
allowed_modes
— a non-empty list of mode IDs in
0 .. K-1
that are allowed to travel on this road
For every mode m:
m
, then traveling along that road:
time_per_edge[m]
minutes
cost_per_edge[m]
units of money
You are also given:
S
— the starting intersection
D
— the destination intersection
time_per_edge[0..K-1]
cost_per_edge[0..K-1]
m
in
0 .. K-1
, considering
only
roads whose
allowed_modes
contains
m
, compute the minimal number of edges from
S
to
D
(if reachable). From that, derive:
T[m] = (number_of_edges_m) * time_per_edge[m]
C[m] = (number_of_edges_m) * cost_per_edge[m]
D
is not reachable from
S
using mode
m
, then that mode should be considered
invalid
for the final choice.
D
, select the
optimal
commute mode according to:
Return:
(T[mode], C[mode])
for that chosen mode.
If no mode can reach D, return an indication that the destination is unreachable (e.g., -1 as the mode and some sentinel values for time and cost).
Some modes may end up with identical (time, cost) pairs (duplicates); your algorithm must still handle these ties correctly.
1 <= N <= 10^5
0 <= M <= 2 * 10^5
1 <= K <= 10
O(N + M)
per mode or better).
K
(time, cost)
pairs must run in
O(K)
time and must
not
sort the list of modes.
Describe your approach, discuss its time and space complexity, and then implement the solution in code.