Bus Routes solution explained

Bus Routes gives you a list of bus lines, each a loop of stops, and asks for the fewest buses you must ride to get from one stop to another, or -1 if you cannot. Run a breadth-first search in waves where each wave means boarding one more bus, and make sure every bus is expanded only once. With a map from stop to buses, the work is proportional to the total length of all routes.

By Published 8 min read

The problem in our own words

A city runs several bus lines. Line i visits the stops in routes[i] over and over, in both directions as far as you are concerned, so you can ride it from any of its stops to any other. You start at stop source, not on a bus, and want to reach stop target. Return the smallest number of buses you need to board. If no combination of buses gets there, return -1.

bus 0: 3, 8, 12
bus 1: 12, 20, 4
bus 2: 4, 9
bus 3: 20, 15, 9
bus 4: 30, 31

source = 3, target = 9   -> 3 buses
source = 3, target = 30  -> -1
source = 8, target = 8   -> 0
A small network invented for this page.

From stop 3 only bus 0 is available, and it reaches 12. At 12 you switch to bus 1, which reaches 20 and 4. From either of those, one more bus (bus 3 from 20, or bus 2 from 4) reaches 9, so three buses in total. Bus 4 shares no stop with any other line, so stop 30 cannot be reached from 3.

What the interviewer is checking

This is a modeling question first. If you search stop to stop and count every hop as one, you answer the wrong question, because riding one bus past five stops still costs one. Interviewers look for you to notice that the cost is per bus, choose a graph where one edge equals one bus boarded, and keep the search from re-reading long routes. Route lists can be long, so the difference between expanding a bus once and expanding it once per stop is often the difference between passing and timing out.

First idea: a graph of buses

Treat each bus as a node. Two buses are connected if they share at least one stop, because you can change between them there. The starting nodes are the buses that call at source, each costing 1, and the search ends at the first bus that calls at target. This gives the right answer and is easy to explain. The weak spot is building the edges: comparing every pair of buses with set intersection costs about O(k² · L) for k buses of length L, which is heavy when there are many buses.

from collections import deque

def fewest_buses_route_graph(routes, source, target):
    if source == target:
        return 0
    stops = [set(r) for r in routes]
    k = len(routes)
    # two buses are linked if they share any stop: compare every pair
    linked = [[j for j in range(k) if j != i and stops[i] & stops[j]] for i in range(k)]
    queue = deque((i, 1) for i in range(k) if source in stops[i])
    seen = {i for i, _ in queue}
    while queue:
        bus, rides = queue.popleft()
        if target in stops[bus]:
            return rides
        for other in linked[bus]:
            if other not in seen:
                seen.add(other)
                queue.append((other, rides + 1))
    return -1
Python: breadth-first search over a bus graph built from pairwise overlaps.

Better: search stops in waves, expand each bus once

Skip the pairwise step by indexing stops. Build a map from each stop to the buses that call there. Then run a breadth-first search over stops in waves: wave 1 is everything reachable on one bus from source, wave 2 is everything reachable with one more bus, and so on. When you pop a stop, look at its buses; for each bus not yet used, mark it used and walk its whole route, adding unseen stops to the next wave. Return the wave number as soon as target appears.

The used-bus marker is what makes this fast. Without it, a bus with many stops is rescanned from every one of those stops, so a single long route can cost its length squared. With it, every route is read once, and every stop enters the queue once.

from collections import deque, defaultdict

def fewest_buses(routes, source, target):
    if source == target:
        return 0
    buses_at = defaultdict(list)  # stop -> buses that call there
    for bus, route in enumerate(routes):
        for stop in route:
            buses_at[stop].append(bus)
    used_bus = [False] * len(routes)
    seen_stop = {source}
    queue = deque([source])
    rides = 0
    while queue:
        rides += 1
        for _ in range(len(queue)):  # one wave = one more bus ridden
            stop = queue.popleft()
            for bus in buses_at[stop]:
                if used_bus[bus]:
                    continue
                used_bus[bus] = True
                for nxt in routes[bus]:
                    if nxt == target:
                        return rides
                    if nxt not in seen_stop:
                        seen_stop.add(nxt)
                        queue.append(nxt)
    return -1
Python: stop-to-bus index, waves by buses boarded.
function fewestBuses(routes, source, target) {
  if (source === target) return 0;
  const busesAt = new Map(); // stop -> list of buses
  routes.forEach((route, bus) => {
    for (const stop of route) {
      if (!busesAt.has(stop)) busesAt.set(stop, []);
      busesAt.get(stop).push(bus);
    }
  });
  const usedBus = new Array(routes.length).fill(false);
  const seenStop = new Set([source]);
  let wave = [source];
  for (let rides = 1; wave.length > 0; rides++) {
    const next = [];
    for (const stop of wave) {
      for (const bus of busesAt.get(stop) ?? []) {
        if (usedBus[bus]) continue;
        usedBus[bus] = true;
        for (const nxt of routes[bus]) {
          if (nxt === target) return rides;
          if (!seenStop.has(nxt)) {
            seenStop.add(nxt);
            next.push(nxt);
          }
        }
      }
    }
    wave = next;
  }
  return -1;
}
JavaScript: the same waves, with a Map for the stop index.

The waves on the example

Wave 1 starts at stop 3. Its only bus is bus 0, which adds 8 and 12. Wave 2 processes 8 (bus 0 already used) and 12, which boards bus 1 and adds 20 and 4. Wave 3 processes 20, boarding bus 3; while walking bus 3's stops it meets 9, the target, and returns 3. Bus 2 is never needed, and bus 4 is never touched.

Stop numbers can be large, so a hash map is safer than an array indexed by stop. Note also that a stop no bus serves can still be the source: if it is not the target, nothing can be boarded and the answer is -1.

Complexity

k buses, S = total number of stops across all routes, L = longest route
ApproachTimeExtra space
Bus graph from pairwise overlapsO(k² · L) to build, then O(k²) to searchO(S + k²)
Stop-by-stop search with no used-bus markerCan reach O(L²) per long routeO(S)
Waves with a used-bus markerO(S)O(S)
k buses, S = total number of stops across all routes, L = longest route. Scroll sideways on a small screen.

Edge cases

  • source equals target: return 0 before building anything.
  • source or target is not on any route: -1, unless they are equal.
  • Several buses share every stop: each is still boarded at most once.
  • A route lists a stop twice: harmless, the seen set ignores the repeat.
  • One very long route that touches everything: the used-bus marker keeps it to a single scan.

Mistakes to avoid

  • Counting stops instead of buses, which returns the number of hops along a route.
  • Forgetting to mark buses used, so long routes are scanned again and again.
  • Returning 1 when source equals target, because the check happens after boarding.
  • Starting the count at 0 and adding one at the wrong place, which makes every answer off by one.
  • Using an array sized by the largest stop number when stop ids may be huge.

Follow-up questions

  • Each bus has a fare and you want the cheapest trip. Edges now have different weights, so use Dijkstra's algorithm on the bus graph instead of plain waves.
  • Return the sequence of buses. Store, for each bus, the bus you were on when you boarded it, then walk back from the last one.
  • Routes change during the day. Rebuild the stop index when a route changes; the search itself stays the same.
  • Search from both ends. A two-sided breadth-first search can cut the explored area when the network is large.

How to explain it

Fictional example

A spoken outline in a mock interview
Candidate
The cost is the number of buses, so riding past several stops on one bus costs one. I want a breadth-first search whose levels are buses boarded.
Candidate
I'll index which buses call at each stop. Then each wave takes the stops I can reach, boards every bus there that I haven't used, and adds all of that bus's stops to the next wave.
Candidate
Marking a bus used the first time means each route is read once, so it's linear in the total number of stops listed.

When each step has its own cost, plain waves are not enough: Path with Maximum Probability and Find the City With the Smallest Number of Neighbors show weighted searches. Minimum Number of Vertices to Reach All Nodes is another question about where a search has to start. For a route-planning puzzle with a different twist, Reconstruct Itinerary uses every ticket exactly once. The coding problems hub lists them all.

Rehearsing graph modeling with Natively

Most wrong answers to Bus Routes come from the model, not the code. In practice on Mac or Windows, Natively can read the problem from a screenshot, and you can ask it to check whether your nodes and edges really count buses before you write anything. It can suggest code when you want to compare against your own, and the transcript of the mock lets you see whether you stated the cost model out loud. See the AI interview assistant page for the coding features.

Questions people ask

How do you solve Bus Routes?

Map each stop to the buses that call there, then run a breadth-first search in waves where each wave boards one more bus. Mark a bus used the first time you board it and return the wave number when the target appears.

Why does Bus Routes count buses instead of stops?

Riding one bus past many stops still costs one bus, so the search levels must be buses boarded, not stops visited.

What is the time complexity of Bus Routes?

O(S), where S is the total number of stops listed across all routes, as long as each bus is expanded only once.

What does Bus Routes return when source equals target?

0, because you are already there and do not need to board any bus.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP