Fewest Bus Rides Between Two Stops on a Transit Map

Last updated: November 29, 2026

Quick Overview

Each bus route is a list of stops it cycles through forever; given a source and target stop, return the minimum number of buses you must board to travel between them, or -1 if impossible.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Each bus route is a list of stops it cycles through forever; given a source and target stop, return the minimum number of buses you must board to travel between them, or -1 if impossible.

Framed around transit directions in Google Maps, this tests whether you pick the right graph abstraction. The interviewer wants to see you realize the cost is per bus, not per stop, and run BFS over routes so that the search does not blow up on dense stops.

What the Interviewer Expects
  • Identifies that edges between consecutive stops give the wrong metric
  • Builds a stop to routes index
  • Runs BFS where each level is one more bus boarded
  • Marks routes as used so each route's stops are expanded only once
  • Handles source equal to target
Key Topics to Cover
Graphs
BFS
Hash Map
Modeling
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Minimize total travel time where each route has a per-stop travel time and boarding has a wait.
  • What if some routes only run during certain hours?
  • How would you precompute answers for millions of queries per second?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: routes (list of lists of stop ids), source, target.
  • A ride on one bus can cover any stops on that route.
  • Output: minimum buses boarded, 0 if source equals target, -1 if unreachable....
High-Level Design

Build stop_to_routes, mapping each stop to the routes that serve it. BFS from the source stop where the frontier is a set of stops and the depth is the number of buses taken. At each level, for ever...


Submit Your Answer
Markdown supported