Magicsheet logo

Bus Routes

Hard
73.2%
Updated 6/1/2025

Bus Routes

What is this problem about?

The Bus Routes interview question is a complex graph problem. You are given a list of bus routes, where each route is a list of stops. You start at a source stop and want to reach a target stop by taking the minimum number of buses. This Bus Routes coding problem isn't just about stops; it's about the connections between different bus lines.

Why is this asked in interviews?

Tech giants like Google, Meta, and Uber use this to test a candidate's ability to model real-world scenarios as graphs. It evaluates whether you can distinguish between "nodes as stops" and "nodes as routes." It also tests your proficiency with Breadth-First Search (BFS) in a multi-layered or transformed graph environment.

Algorithmic pattern used

This problem follows the Array, Breadth-First Search, Hash Table interview pattern. Instead of a standard BFS on stops, it's more efficient to perform a BFS where each node represents a bus route.

  1. Build a map of stop -> list of routes that pass through it.
  2. Use BFS starting from all routes that pass through the source.
  3. In each step of BFS, explore all unvisited routes that can be reached by any stop on the current route.
  4. The first time you encounter a route that includes the target, return the distance.

Example explanation

Route 0: [1, 2, 7], Route 1: [3, 6, 7]. Source: 1, Target: 6.

  1. Stop 7 is common to both routes.
  2. At Stop 1, we take Route 0 (1 bus).
  3. From Route 0, we can get off at Stop 7 and transfer to Route 1.
  4. Route 1 takes us to Stop 6. Total buses: 2.

Common mistakes candidates make

  • BFS on stops: Treating every stop as a node. Since there can be thousands of stops, this makes the graph too dense and leads to TLE.
  • Re-visiting stops: Not keeping track of which routes have already been taken, leading to redundant calculations and infinite loops.
  • Initialization: Forgetting to handle the edge case where the source and target are the same (should return 0).

Interview preparation tip

When solving graph problems, always consider what the most efficient "node" should be. Often, transforming the problem (e.g., from stops to routes) significantly reduces the number of edges the BFS needs to traverse.

Similar Questions