Find minimum shuttle transfers
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: Find minimum shuttle transfers evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= routes.length <= 500
- 1 <= sum(routes[i].length) <= 100000
- All stop IDs within a single loop are distinct.
- 0 <= source, target, and all stop IDs.
Examples
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
Expected Output: 2
Explanation: Board loop 0 at stop 1, ride to stop 7, transfer to loop 1, ride to stop 6. Two boardings.
Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
Expected Output: -1
Explanation: Loops containing 15 ({4,5,15} and {15,19}) share no stop with any loop reaching 12, so the target is unreachable.
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 1
Expected Output: 0
Explanation: Source equals target, so no shuttle needs to be boarded.
Input: routes = [[1,2,3]], source = 1, target = 3
Expected Output: 1
Explanation: A single loop serves both stops; one boarding suffices.
Input: routes = [[1,2,3]], source = 1, target = 5
Expected Output: -1
Explanation: Stop 5 is not served by any loop, so it is unreachable.
Input: routes = [[1,7],[3,5]], source = 5, target = 5
Expected Output: 0
Explanation: Source equals target even though the loops are isolated; the answer is 0.
Input: routes = [[1,2],[2,3],[3,4],[4,5]], source = 1, target = 5
Expected Output: 4
Explanation: Each consecutive loop overlaps the next at one stop, forcing four chained boardings: loop0->loop1->loop2->loop3.
Input: routes = [[0,1,6,16,22,23],[14,15,24,32],[4,10,12,20,24,28,33],[1,10,11,19,27,33],[11,23,25,28],[22,23,38],[0,7,8,14,24,30,32]], source = 7, target = 23
Expected Output: 2
Explanation: Board loop 6 (contains 7) to reach stop 0, then board loop 0 (shares stop 0) which serves stop 23. Two boardings.
Hints
- Model this as a shortest-path problem where the 'cost' is the number of shuttles boarded, not the number of stops traveled. A plain BFS over stops counts stops, which is the wrong metric.
- Pre-compute a map from each stop ID to the list of loop indices that serve it. This lets you jump from a stop to every loop reachable in one boarding.
- Run a level-order BFS starting from the source stop. Each BFS level corresponds to one additional shuttle. When you visit a stop, expand every not-yet-used loop through that stop and enqueue all of that loop's stops.
- Mark whole loops as visited (not just stops) so you never re-expand the same loop. Handle source == target up front as the answer 0.