Minimize Bus Boardings between Two Stops

Quick Overview

Minimize Bus Boardings between Two Stops. Each routes[i] lists the stops visited forever in a cycle by bus i.

Minimize Bus Boardings between Two Stops

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem Each routes[i] lists the stops visited forever in a cycle by bus i. Start at source on no bus and travel only by riding buses, transferring at shared stops. Return the minimum number of buses boarded to reach target, or -1 if unreachable. If source equals target, no bus is needed. ```cpp class Solution { public: int numBusesToDestination(vector<vector<int>>& routes, int source, int target); }; ``` ### Examples **Example 1:** ```text routes = [[2,4,8],[8,9]], source = 2, target = 9 Output: 2 Explanation: Ride the first bus to8 and transfer to the second. ``` **Example 2:** ```text routes = [[1,2]], source = 7, target = 7 Output: 0 Explanation: You are already at the destination. ``` ### Constraints - Route count is 1 through 500. - Each route has 1 through 100000 distinct stops, and total listed stops do not exceed 100000. - Stop labels, source and target are integers in [0,999999]. ### Contract considerations Keep cyclic reachability and transfer-at-shared-stop semantics. ```hint Read the boundary condition What entire set of stops becomes reachable after one boarding? ``` ### Boundary reminders Keep cyclic reachability and transfer-at-shared-stop semantics.

Overview: Minimize Bus Boardings between Two Stops. Each routes[i] lists the stops visited forever in a cycle by bus i.

Amazon logo
Amazon
Source window: 0–3 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Each routes[i] lists the stops visited forever in a cycle by bus i. Start at source on no bus and travel only by riding buses, transferring at shared stops. Return the minimum number of buses boarded to reach target, or -1 if unreachable. If source equals target, no bus is needed.

class Solution {
public:
    int numBusesToDestination(vector<vector<int>>& routes, int source, int target);
};

Examples

Example 1:

routes = [[2,4,8],[8,9]], source = 2, target = 9
Output: 2
Explanation: Ride the first bus to8 and transfer to the second.

Example 2:

routes = [[1,2]], source = 7, target = 7
Output: 0
Explanation: You are already at the destination.

Constraints

  • Route count is 1 through 500.
  • Each route has 1 through 100000 distinct stops, and total listed stops do not exceed 100000.
  • Stop labels, source and target are integers in [0,999999].

Contract considerations

Keep cyclic reachability and transfer-at-shared-stop semantics.

Boundary reminders

Keep cyclic reachability and transfer-at-shared-stop semantics.