Minimum Rides Across Circular Shuttle Lines
Trees & GraphsAuto-graded · 23 test casesLast updated
Find the fewest shuttle lines to board to get from one stop to another, using a graph search over lines and a stop-to-lines index to stay linear in total stops.
A transit system has several shuttle lines. Each line travels around a fixed circular list of stops, again and again without end. A passenger on a line can ride from any stop on it to any other stop on the same line. Passengers may get on or off only at stops that belong to the line they are using.
You begin at stop start, not aboard any shuttle, and you want to arrive at stop goal. To change lines, you get off at a stop that both lines serve and board the other one there.
Return the smallest number of shuttles you need to board to get from start to goal, or -1 if it is impossible.
lines[i] is the list of stops that line i serves, in the order the shuttle visits them. After the last stop it goes back to the first. start and goal are stop IDs.
Rules
- Every boarding counts as one ride, including the first. Riding a single line between any two of its stops counts as one ride, no matter how many stops are passed.
- If
start == goal, the answer is0, even if no line serves that stop. - Otherwise, if no sequence of boardings leads to
goal, return-1. This includes the case wherestartorgoalis not served by any line. - Lines can be changed only at a stop shared by both lines. Walking between different stops is not allowed.
- The result is a single integer.
Constraints
1 <= len(lines) <= 5001 <= len(lines[i]) <= 10^5sum(len(l) for l in lines) <= 10^5- Stops within a single line are distinct; the same stop can appear on many lines.
0 <= lines[i][j] < 10^60 <= start, goal < 10^6- All values fit in a signed 32-bit integer.
Examples
Example 1
Input: min_shuttle_rides([[2, 4, 9], [9, 11, 5], [5, 13], [4, 5]], 4, 13)
Output: 2
Example 2
Input: min_shuttle_rides([[1, 3, 5], [2, 4], [4, 8]], 3, 8)
Output: -1
Example 3
Input: min_shuttle_rides([[7, 12]], 3, 3)
Output: 0
Hints
Hint 1
The order of stops around the loop does not matter: riding one line from any of its stops to any other costs exactly one ride. Treat each line as a set of stops.
Hint 2
Search over lines instead of stops. Two lines are neighbours if they share a stop. Starting lines (those serving start) are at distance 1, since the first boarding counts.
Hint 3
Do not build line-to-line edges pairwise. Keep a map from each stop to the lines serving it, and expand each stop only once during a breadth-first search, along with a visited flag per line.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The cost is the number of boardings, not the number of stops passed. Since a rider can go from any stop of a line to any other stop of that line for one ride, the loop order is irrelevant. Each line is just a set of stops.
This turns the task into a shortest-path problem on an unweighted graph whose nodes are lines, with two lines adjacent when they share a stop. The lines serving start are at distance 1 (the first boarding counts). The answer is the smallest distance of any line that serves goal.
Building all line-to-line edges would be wasteful, because two lines may share many stops. Instead we build a map from each stop to the lines serving it and run a BFS over lines:
- Handle
start == goalfirst and return0. - Build the stop-to-lines map. If
startorgoalis in no line, return-1. - Enqueue every line serving
startwith distance 1. - Pop a line with distance
dand scan its stops. If any stop isgoal, returnd. - For each stop not yet expanded, mark it expanded and enqueue every unvisited line through it with distance
d + 1.
Why it is correct
- Every boarding costs 1, so BFS pops lines in nondecreasing distance order, and a line's distance when first enqueued is the minimum number of rides needed to be on it.
- The first popped line that contains
goalhas the minimum distance among all lines containinggoal, so no solution with fewer rides exists. - Transfers happen only at shared stops, which is exactly how new lines get enqueued.
- Expanding a stop only once is safe: the first expansion enqueues all its lines at the smallest possible distance, and later expansions could only offer larger ones.
- The
start == goalcheck comes before the unserved-stop check, so an unserved stop that is both start and goal returns0.
Complexity
Let N be the total number of stops over all lines and R the number of lines.
- Time:
O(N + R). Each line is dequeued at most once and scanned once, and each stop's line list is walked at most once. - Space:
O(N + R)for the map, visited structures and queue.
Reference solution
from collections import deque
from typing import List
def min_shuttle_rides(lines: List[List[int]], start: int, goal: int) -> int:
if start == goal:
return 0
# Map each stop to the lines that serve it.
stop_lines = {}
for i, line in enumerate(lines):
for s in line:
stop_lines.setdefault(s, []).append(i)
if start not in stop_lines or goal not in stop_lines:
return -1
seen_line = [False] * len(lines)
seen_stop = {start}
q = deque()
# Boarding any line that serves start costs one ride.
for i in stop_lines[start]:
seen_line[i] = True
q.append((i, 1))
while q:
i, d = q.popleft()
for s in lines[i]:
if s == goal:
return d
if s in seen_stop:
continue
seen_stop.add(s)
# Transfer at s onto any line not yet used.
for j in stop_lines[s]:
if not seen_line[j]:
seen_line[j] = True
q.append((j, d + 1))
return -1