Fewest Transit Lines to Board Between Two Stops

Last updated: November 29, 2026

Quick Overview

Given transit lines, each a list of stop ids it serves in a loop, plus a source and target stop, return the minimum number of lines a rider must board to travel from source to target, or -1 if impossible.

Uber
Coding & Algorithms
Software Engineer
Uber
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given transit lines, each a list of stop ids it serves in a loop, plus a source and target stop, return the minimum number of lines a rider must board to travel from source to target, or -1 if impossible.

Uber's app surfaces public transit options in many cities alongside rides, so multimodal routing is part of the product. The onsite interviewer checks whether you choose the right graph: BFS over lines rather than over stops, which keeps the search from blowing up on busy hub stops.

What the Interviewer Expects
  • Identify that the cost is lines boarded, not stops traveled
  • Build a stop to lines index
  • BFS where each level is one more line boarded
  • Mark both lines and stops visited to avoid rework
  • Handle source equal to target
Key Topics to Cover
BFS
graph modeling
bipartite stop-line graph
hash map index
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
  • What if each line has a fare and you want the cheapest trip with at most 2 transfers?
  • How would you add a walking transfer between nearby stops?
  • How would you precompute answers for a city with 10,000 lines and heavy query volume?
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: lines, list of lists of stop ids; source, target.
  • Riding a line lets you reach any of its stops. Boarding counts 1.
  • Output: minimum boardings, 0 if source == target, -1 if unr...
High-Level Design

Think of a bipartite graph of stops and lines. Build stop_to_lines. Start BFS with every line serving source at depth 1. When a line is dequeued, scan its stops: if any is the target, return the d...


Submit Your Answer
Markdown supported