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 0 whenever source == target, even if no route in routes visits that stop.
  • Return -1 if source != target and no sequence of bus rides connects source to target (including when source or target is 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) <= 500
  • 1 <= len(routes[i]) <= 10^5
  • sum(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^6
  • 0 <= source, target < 10^6

Step-by-step walkthrough

  1. Restate the rules and why stop order does not matter

    We receive routes, where routes[i] lists the distinct stops visited by circular bus route i, along with a starting stop source and destination stop target. We want the minimum number of buses boarded to travel from source to target (or -1 if target cannot be reached).

    Two observations shape the entire solution:

    1. Every route loops endlessly: Once you step onto route i at any of its stops, staying aboard reaches every other stop in routes[i] (even stops listed earlier in the array) within that single boarding. Consequently, the order of stops inside routes[i] does not affect the answer — only stop membership matters.
    2. Zero boardings when source == target: If you already start at target, you board 0 buses — even when no route in routes visits that stop (Example 3).
  2. 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,000 stops:

    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?"

  3. 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 +1 boarding. Because every transition costs 1 bus, breadth-first search (BFS) — expanding outward in waves with a first-in, first-out queue — explores all 1-bus routes before any 2-bus routes, all 2-bus routes before any 3-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 target is guaranteed to use the fewest possible boardings.

  4. 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 by k routes). Instead, we build one lookup map lines_at_stop[stop] -> [routes serving stop] in a single O(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_stop
    

    Watch out for one subtle performance trap during BFS: suppose 500 routes all share 200 downtown stops. If every popped route scans all 200 stops and iterates through all 500 routes at each stop, we perform 500 * 200 * 500 = 50,000,000 checks!

    Notice that the very first time we expand a stop s, we queue every unboarded route in lines_at_stop[s]. Visiting s again later from another route can never discover a new unboarded route there! Recording s inside expanded_stops ensures lines_at_stop[s] is scanned at most once across the entire search, keeping total work strictly O(R + S).

  5. Code the special cases and the BFS loop

    Check source == target first (returning 0), then build lines_at_stop and return -1 if either endpoint is absent from the network. Seed queue with every route serving source at cost 1, mark boarded[line_idx] = True when pushing onto the queue so no route is queued twice, and start expanded_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 -1
    
  6. Walk 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!
    
  7. 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). Building lines_at_stop visits each of the S stop entries once (O(S)). During BFS, boarded ensures each of the R routes enters and leaves queue at most once, so scanning routes[line_idx] across the whole run touches at most S entries. Meanwhile, expanded_stops ensures each stop's lines_at_stop[stop] list is iterated at most once across the whole run, touching at most S entries again.
  • Space: O(R + S). The lines_at_stop dictionary stores S route indices in total across at most S distinct stops, expanded_stops holds at most S stop IDs, and boarded, target_lines, and queue each hold at most R items.

Edge cases

  • source == target (0 buses, Example 3): Must return 0 before checking whether source appears in lines_at_stop, because 0 boardings are needed even at an isolated stop visited by zero routes.
  • source or target visited by zero routes (when source != target): Caught immediately by source not in lines_at_stop or target not in lines_at_stop, returning -1.
  • source and target on the same route (1 bus): Works regardless of whether target sits before or after source in routes[i], because every route loops continuously.
  • Disconnected transit components (Example 2): queue drains all routes reachable from source without hitting target_lines and returns -1.
  • Long linear chain of 500 routes ([0, 1], [1, 2], ..., [499, 500]): Advances through all 500 waves cleanly and returns 500.
  • Heavy hub overlap (500 routes sharing 200 common stops): expanded_stops skips each shared stop after the first route expands it, keeping runtime instant instead of scanning 50,000,000 pairs.

Common mistakes

  • Checking source not in lines_at_stop before source == target: Wrongly returns -1 instead of 0 on Example 3 (routes = [[4, 9, 18]], source = 25, target = 25).
  • Counting transfers instead of boardings: Returning 0 for a single-bus ride (1 bus) by forgetting the initial boarding counts as 1.
  • 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 boarded when popping from queue instead of when pushing: Lets dozens of shared stops in the current wave push duplicate copies of the same next_line into queue.
  • Forgetting expanded_stops: Still produces the right answer, but degrades worst-case time from O(R + S) to O(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 return 3 boardings (0 -> 1 -> 2 in Example 1) when a 2-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 source with cost 0, stop-to-route edges cost 1 (boarding) and route-to-stop edges cost 0 (or every edge costs 1 and the final distance is divided by 2). Maintaining visited sets for both stops and routes performs the exact same O(R + S) work as our boarded + expanded_stops search.
  • Bidirectional BFS: Run bidirectional BFS (two simultaneous wave searches, expanding forward from source's routes and backward from target's routes, always advancing whichever frontier is smaller) until both frontiers share a route or stop. Worst-case time stays O(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 parent dictionary mapping each newly queued next_line to (line_idx, stop) (the preceding route and the transfer stop that discovered it), storing (-1, source) for initial routes. Once line_idx in target_lines triggers, walk parent backward 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 1 stop forward is much faster than looping 99 stops 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 on routes[current_route] (cost = hop minutes) and switching to another route at stop (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 <= 500 is small, precompute an R x R matrix route_dist[a][b] storing the fewest transfers between every pair of routes by running our O(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 in O(|routes(source)| * |routes(target)|) array lookups via 1 + min(route_dist[a][b]) across a in lines_at_stop[source] and b in lines_at_stop[target].

Follow-up questions

Similar questions

More Pinterest interview questions

All 161 Pinterest questions →