Minimum Boardings on Circular Bus Routes
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A transit network operates several circular bus routes. Route i is described by an integer list routes[i] giving the distinct stop IDs along its loop; once a bus reaches the end of routes[i], it wraps directly back to routes[i][0] and continues indefinitely. Because every route repeats forever, boarding route i at any of its stops lets a passenger reach every other stop on route i within that single ride.
You begin on foot at stop source and want to reach stop target. You can step onto or off a bus only at stops listed on its route, and you can switch routes only at a shared stop served by both routes (walking between different stop IDs is not allowed). Every bus you step onto adds 1 to your total, regardless of how many stops you ride along that loop.
Implement min_buses(routes, source, target) to return the minimum number of bus boardings required to travel from source to target:
- Return
0wheneversource == target, even if no route inroutesvisits that stop. - Return
-1ifsource != targetand no sequence of bus rides connectssourcetotarget(including whensourceortargetis absent from every route).
Examples
Example 1
Input: routes = [[1, 6, 10], [10, 14, 20], [20, 30], [6, 20]], source = 6, target = 30
Output: 2
Board route 3 ([6, 20]) at stop 6 and ride to stop 20, then transfer to route 2 ([20, 30]) to reach stop 30 in 2 boardings. Taking routes 0 -> 1 -> 2 (6 -> 10 -> 20 -> 30) would require 3 boardings, and no single route visits both 6 and 30.
Example 2
Input: routes = [[3, 7, 12], [5, 15], [15, 22]], source = 7, target = 22
Output: -1
Stop 7 is visited only by route 0 ([3, 7, 12]), and none of {3, 7, 12} appear on route 1 or route 2, so stop 22 is unreachable.
Example 3
Input: routes = [[4, 9, 18]], source = 25, target = 25
Output: 0
Because source and target are already the same stop (25), 0 buses are boarded even though stop 25 does not belong to any route.
Constraints
1 <= len(routes) <= 5001 <= len(routes[i]) <= 10^5sum(len(r) for r in routes) <= 10^5- All stop IDs within a single
routes[i]are unique; different routes may share stop IDs. 0 <= routes[i][j] < 10^60 <= source, target < 10^6
Step-by-step walkthrough
Restate the rules and why stop order does not matter
We receive
routes, whereroutes[i]lists the distinct stops visited by circular bus routei, along with a starting stopsourceand destination stoptarget. We want the minimum number of buses boarded to travel fromsourcetotarget(or-1iftargetcannot be reached).Two observations shape the entire solution:
- Every route loops endlessly: Once you step onto route
iat any of its stops, staying aboard reaches every other stop inroutes[i](even stops listed earlier in the array) within that single boarding. Consequently, the order of stops insideroutes[i]does not affect the answer — only stop membership matters. - Zero boardings when
source == target: If you already start attarget, you board0buses — even when no route inroutesvisits that stop (Example 3).
- Every route loops endlessly: Once you step onto route
Why a stop-to-stop graph is too slow
Connecting every pair of stops on the same route directly turns each route into a dense clique. Look at what happens when a single route has
100,000stops:Stop-to-stop clique on one 5-stop route [A, B, C, D, E]: Every stop connects to every other stop -> 5 * 4 / 2 = 10 edges. On a 100,000-stop route -> 100,000 * 99,999 / 2 ≈ 5,000,000,000 edges! (Memory & time blowup) Route-level view of the exact same data: Only R <= 500 routes exist, and total stop entries S = sum(len(r)) <= 100,000!Instead of asking "which stop am I standing on?", ask "which bus route am I riding?"
Key idea: breadth-first search over bus routes
Model each bus route as a search state. Two routes connect whenever they share at least one stop, and switching routes adds
+1boarding. Because every transition costs1bus, breadth-first search (BFS) — expanding outward in waves with a first-in, first-out queue — explores all1-bus routes before any2-bus routes, all2-bus routes before any3-bus routes, and so on.Example 1: routes = [[1, 6, 10], [10, 14, 20], [20, 30], [6, 20]], source = 6, target = 30 source = 6 |-- Wave 1 (1 bus): Route 0 [1, 6, 10] Route 3 [6, 20] | | (via stop 10) | (via stop 20) |-- Wave 2 (2 buses): Route 1 [10, 14, 20] Route 2 [20, 30] <-- serves target 30!The very first popped route that visits
targetis guaranteed to use the fewest possible boardings.Keep transfers linear with a stop index and expanded_stops
We do not need to compare route pairs upfront (which would create
O(k^2)edges at a hub shared bykroutes). Instead, we build one lookup maplines_at_stop[stop] -> [routes serving stop]in a singleO(S)pass:from typing import Dict, List def build_stop_index(routes: list[list[int]]) -> Dict[int, List[int]]: """Map each stop ID to the list of bus line indices that serve it.""" # lines_at_stop: {stop_id: [line_index, ...]} lines_at_stop: Dict[int, List[int]] = {} for line_idx, stops in enumerate(routes): for stop in stops: if stop not in lines_at_stop: lines_at_stop[stop] = [] lines_at_stop[stop].append(line_idx) return lines_at_stopWatch out for one subtle performance trap during BFS: suppose
500routes all share200downtown stops. If every popped route scans all200stops and iterates through all500routes at each stop, we perform500 * 200 * 500 = 50,000,000checks!Notice that the very first time we expand a stop
s, we queue every unboarded route inlines_at_stop[s]. Visitingsagain later from another route can never discover a new unboarded route there! Recordingsinsideexpanded_stopsensureslines_at_stop[s]is scanned at most once across the entire search, keeping total work strictlyO(R + S).Code the special cases and the BFS loop
Check
source == targetfirst (returning0), then buildlines_at_stopand return-1if either endpoint is absent from the network. Seedqueuewith every route servingsourceat cost1, markboarded[line_idx] = Truewhen pushing onto the queue so no route is queued twice, and startexpanded_stops = {source}:from collections import deque def min_buses(routes: list[list[int]], source: int, target: int) -> int: """Return the fewest bus boardings from source to target, or -1 if unreachable.""" # Phase 1: Handle trivial and impossible endpoints. # Check source == target BEFORE checking lines_at_stop: even if that stop is on # zero bus lines (Example 3), you are already there and need 0 buses. if source == target: return 0 lines_at_stop = build_stop_index(routes) if source not in lines_at_stop or target not in lines_at_stop: return -1 # target_lines: set of line indices that pass through target for O(1) goal checks. target_lines = set(lines_at_stop[target]) # Phase 2: Seed BFS with every bus line serving `source` at cost = 1 boarding. # boarded[line_idx]: True as soon as line_idx enters the queue (prevents duplicates). # queue: FIFO deque of (line_idx, buses_boarded_so_far). boarded = [False] * len(routes) queue = deque() for line_idx in lines_at_stop[source]: boarded[line_idx] = True queue.append((line_idx, 1)) # expanded_stops: stop IDs whose transfer list lines_at_stop[stop] was already used. # Once a stop is expanded once, every bus line through it is already queued, # so skipping it later keeps heavy hub-sharing networks O(R + S) instead of O(R * S). expanded_stops = {source} # Phase 3: Expand lines wave by wave in increasing order of buses boarded. while queue: line_idx, buses = queue.popleft() if line_idx in target_lines: return buses for stop in routes[line_idx]: if stop in expanded_stops: continue expanded_stops.add(stop) for next_line in lines_at_stop[stop]: if not boarded[next_line]: boarded[next_line] = True queue.append((next_line, buses + 1)) return -1Walk through Example 1 step by step
Let's trace
routes = [[1, 6, 10], [10, 14, 20], [20, 30], [6, 20]],source = 6,target = 30:lines_at_stop: {1: [0], 6: [0, 3], 10: [0, 1], 14: [1], 20: [1, 2, 3], 30: [2]} target_lines: {2} Seed from source = 6: queue = [(0, 1), (3, 1)], boarded = [T, F, F, T], expanded_stops = {6} Step 1: pop (0, 1) -> 0 not in {2}. Scan routes[0] = [1, 6, 10]: - stop 1: expand -> lines [0] (already boarded) - stop 6: already in expanded_stops -> skip - stop 10: expand -> lines [0, 1] -> queue (1, 2), boarded[1] = True queue = [(3, 1), (1, 2)], expanded_stops = {6, 1, 10} Step 2: pop (3, 1) -> 3 not in {2}. Scan routes[3] = [6, 20]: - stop 6: already in expanded_stops -> skip - stop 20: expand -> lines [1, 2, 3] -> queue (2, 2), boarded[2] = True queue = [(1, 2), (2, 2)], expanded_stops = {6, 1, 10, 20} Step 3: pop (1, 2) -> 1 not in {2}. Scan routes[1] = [10, 14, 20]: - stops 10, 20: skip; stop 14: expand -> lines [1] (already boarded) queue = [(2, 2)] Step 4: pop (2, 2) -> 2 IS in target_lines {2} -> return 2!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def build_stop_index(routes: list[list[int]]) -> Dict[int, List[int]]: """Map each stop ID to the list of bus line indices that serve it.""" # lines_at_stop: {stop_id: [line_index, ...]} lines_at_stop: Dict[int, List[int]] = {} for line_idx, stops in enumerate(routes): for stop in stops: if stop not in lines_at_stop: lines_at_stop[stop] = [] lines_at_stop[stop].append(line_idx) return lines_at_stop def min_buses(routes: list[list[int]], source: int, target: int) -> int: """Return the fewest bus boardings from source to target, or -1 if unreachable.""" # Phase 1: Handle trivial and impossible endpoints. # Check source == target BEFORE checking lines_at_stop: even if that stop is on # zero bus lines (Example 3), you are already there and need 0 buses. if source == target: return 0 lines_at_stop = build_stop_index(routes) if source not in lines_at_stop or target not in lines_at_stop: return -1 # target_lines: set of line indices that pass through target for O(1) goal checks. target_lines = set(lines_at_stop[target]) # Phase 2: Seed BFS with every bus line serving `source` at cost = 1 boarding. # boarded[line_idx]: True as soon as line_idx enters the queue (prevents duplicates). # queue: FIFO deque of (line_idx, buses_boarded_so_far). boarded = [False] * len(routes) queue = deque() for line_idx in lines_at_stop[source]: boarded[line_idx] = True queue.append((line_idx, 1)) # expanded_stops: stop IDs whose transfer list lines_at_stop[stop] was already used. # Once a stop is expanded once, every bus line through it is already queued, # so skipping it later keeps heavy hub-sharing networks O(R + S) instead of O(R * S). expanded_stops = {source} # Phase 3: Expand lines wave by wave in increasing order of buses boarded. while queue: line_idx, buses = queue.popleft() if line_idx in target_lines: return buses for stop in routes[line_idx]: if stop in expanded_stops: continue expanded_stops.add(stop) for next_line in lines_at_stop[stop]: if not boarded[next_line]: boarded[next_line] = True queue.append((next_line, buses + 1)) return -1✅ Submit now — all tests should pass.
Intuition & how it works
Picture a transit map where every color-coded shuttle runs around a closed loop forever. Once you step onto the Green Shuttle, riding 1 stop or 40 stops still counts as 1 shuttle boarded — your count only climbs when you step onto a shared platform and switch to another loop! That observation flips the graph on its head: the states we step between are bus routes, linked whenever two routes share a transfer stop.
Why do simpler graph models bog down? Connecting every pair of stops on the same route directly turns a 100,000-stop route into roughly 5 billion stop-to-stop edges, exhausting memory right away. Even if you treat routes as nodes, precomputing all route-to-route edges at busy hubs (O(R^2)) or rescanning a shared stop's route list for every bus passing through it (O(R * S)) wastes tens of millions of checks. Instead, we build an inverted index (a dictionary mapping each stop to the list of routes visiting it) and run breadth-first search (BFS) (a wave-by-wave graph search using a first-in, first-out queue so all 1-bus rides finish before any 2-bus rides), marking both queued routes and already-expanded stops so every (route, stop) entry is inspected at most twice.
Here is a quick trace on routes = [[1, 6, 10], [10, 14, 20], [20, 30], [6, 20]] from source = 6 to target = 30:
- Wave 1 (1 bus from stop 6): queue Route 0 [1, 6, 10] and Route 3 [6, 20].
- Pop Route 0 (1 bus): not at 30; stop 10 discovers Route 1 -> queue (Route 1, 2 buses).
- Pop Route 3 (1 bus): not at 30; stop 20 discovers Route 2 -> queue (Route 2, 2 buses).
- Pop Route 1 (2 buses): not at 30.
- Pop Route 2 (2 buses): Route 2 visits stop 30 -> return 2!
Complexity
Let R be the number of routes (len(routes)) and S be the sum of stop entries across all routes (sum(len(r) for r in routes)).
- Time:
O(R + S). Buildinglines_at_stopvisits each of theSstop entries once (O(S)). During BFS,boardedensures each of theRroutes enters and leavesqueueat most once, so scanningroutes[line_idx]across the whole run touches at mostSentries. Meanwhile,expanded_stopsensures each stop'slines_at_stop[stop]list is iterated at most once across the whole run, touching at mostSentries again. - Space:
O(R + S). Thelines_at_stopdictionary storesSroute indices in total across at mostSdistinct stops,expanded_stopsholds at mostSstop IDs, andboarded,target_lines, andqueueeach hold at mostRitems.
Edge cases
source == target(0buses, Example 3): Must return0before checking whethersourceappears inlines_at_stop, because0boardings are needed even at an isolated stop visited by zero routes.sourceortargetvisited by zero routes (whensource != target): Caught immediately bysource not in lines_at_stop or target not in lines_at_stop, returning-1.sourceandtargeton the same route (1bus): Works regardless of whethertargetsits before or aftersourceinroutes[i], because every route loops continuously.- Disconnected transit components (Example 2):
queuedrains all routes reachable fromsourcewithout hittingtarget_linesand returns-1. - Long linear chain of 500 routes (
[0, 1], [1, 2], ..., [499, 500]): Advances through all500waves cleanly and returns500. - Heavy hub overlap (
500routes sharing200common stops):expanded_stopsskips each shared stop after the first route expands it, keeping runtime instant instead of scanning50,000,000pairs.
Common mistakes
- Checking
source not in lines_at_stopbeforesource == target: Wrongly returns-1instead of0on Example 3 (routes = [[4, 9, 18]], source = 25, target = 25). - Counting transfers instead of boardings: Returning
0for a single-bus ride (1bus) by forgetting the initial boarding counts as1. - Building a stop-to-stop adjacency graph: Generates
O(len(route)^2)edges per route and times out on long loops (len(route) = 10^5). - Marking
boardedwhen popping fromqueueinstead of when pushing: Lets dozens of shared stops in the current wave push duplicate copies of the samenext_lineintoqueue. - Forgetting
expanded_stops: Still produces the right answer, but degrades worst-case time fromO(R + S)toO(R * S)when many routes share hubs. - Using depth-first search (DFS) instead of BFS: DFS follows the first transfer chain it encounters all the way to
target, which can return3boardings (0 -> 1 -> 2in Example 1) when a2-boarding trip (3 -> 2) exists.
Alternative approaches
- Explicit bipartite graph BFS (stops + routes): Treat both stops and routes as vertices in a bipartite graph (a graph partitioned into two vertex sets where edges only connect a stop to a route serving it). Starting at
sourcewith cost0, stop-to-route edges cost1(boarding) and route-to-stop edges cost0(or every edge costs1and the final distance is divided by2). Maintaining visited sets for both stops and routes performs the exact sameO(R + S)work as ourboarded+expanded_stopssearch. - Bidirectional BFS: Run bidirectional BFS (two simultaneous wave searches, expanding forward from
source's routes and backward fromtarget's routes, always advancing whichever frontier is smaller) until both frontiers share a route or stop. Worst-case time staysO(R + S), while dense transit networks explore far fewer routes in practice.
Follow-up questions
- How would you reconstruct the actual sequence of bus routes and transfer stops rather than returning only the boarding count? Maintain a
parentdictionary mapping each newly queuednext_lineto(line_idx, stop)(the preceding route and the transfer stop that discovered it), storing(-1, source)for initial routes. Onceline_idx in target_linestriggers, walkparentbackward to(-1, source)and reverse the chain to output every boarded route and transfer stop in chronological order. - How would the model change if each stop-to-stop hop and each transfer had a travel or wait duration in minutes, and you wanted the fastest arrival? Hop counts and loop direction now matter (riding
1stop forward is much faster than looping99stops around!), giving edges non-uniform positive weights where plain BFS no longer applies. Model states as(stop, current_route)with weighted directed edges for advancing to the next stop onroutes[current_route](cost = hop minutes) and switching to another route atstop(cost = transfer wait minutes), then run Dijkstra's algorithm (shortest-path search that repeatedly pops the minimum cumulative-time state from a min-heap). - If the route network is fixed and millions of (source, target) queries arrive, how could you preprocess the graph for fast lookups? Because
R <= 500is small, precompute anR x Rmatrixroute_dist[a][b]storing the fewest transfers between every pair of routes by running ourO(R + S)BFS once from each route (O(R * (R + S))one-time setup, well under a second). Each online query(source, target)then answers inO(|routes(source)| * |routes(target)|)array lookups via1 + min(route_dist[a][b])acrossa in lines_at_stop[source]andb in lines_at_stop[target].
Follow-up questions
- How would you reconstruct the actual sequence of bus routes and transfer stops rather than returning only the boarding count?
- How would the model change if each stop-to-stop hop and each transfer had a travel or wait duration in minutes, and you wanted the fastest arrival?
- If the route network is fixed and millions of (source, target) queries arrive, how could you preprocess the graph for fast lookups?
Similar questions
- Time-Indexed Moderation Log Queries
- Masonry Column Height Allocation
- Percentile Bootstrap Interval for Mean Order Amount
- Unique Pin Traversal Over Linked Boards
- Mean Distinct Saved Pins Across Users
- Count Reachable Tiles Within Step Limit
More Pinterest interview questions
- Prune and Reindex a Parent-Array Forest Medium
- Time-Indexed Moderation Log Queries Medium
- Confusion Matrix Metrics and ML Foundations Hard Pro
- Multi-Topic Behavioral Onsite: Metrics, Leadership, Team Dynamics, and Conflict Hard Pro
- Seven-Day Highly Active User Share by Country Medium Pro
- Bootstrap Aggregating Classifier Over Decision Trees Hard Pro
- Closest Qualifying Elevator Medium Pro
- Balance Group IOUs with Fewer Transfers Medium Pro
- Clearing Shared Expenses in Minimal Transfers Medium Pro
- Minimum-Transfer Ledger Settlement Medium Pro