FastPrepBus Routes
Problems/Bus Routes

Bus Routes

UiPath logoUiPath● HardFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: In the first DSA round, the candidate was given two hard questions in 50 minutes. They said both were small changes to well-known problems, and this one was Bus Routes.

The report does not say what the change was. Here you get the standard version: return the fewest buses from source to target, -1 when it cannot be done, and 0 when source and target are the same. Routes hold at most 10^4 stops in total.

The judged task matches the report at about 70%.

You are given an array routes, where routes[i] lists the bus stops that bus i visits. Each bus drives its route in a loop forever, so once you are on bus i, you can ride it to any stop in routes[i].

You start at bus stop source and you are not on a bus yet. You want to reach bus stop target. You can travel only by bus, and you can change from one bus to another at any stop that both buses visit.

Return the least number of buses you must take to reach target. Return -1 if you cannot reach it. If source equals target, return 0, because you are already there.

Function

numBusesToDestination(routes: int[][], source: int, target: int) → int

Examples

Example 1

routes = [[2,5,9],[9,4,1],[1,8,3],[6,7]]source = 5target = 3return = 3

Take bus 0 from stop 5 to stop 9. Change to bus 1 and ride it to stop 1. Change to bus 2 and ride it to stop 3. That is 3 buses.

No single bus or pair of buses works. Only bus 0 stops at 5, and it shares a stop only with bus 1, which does not stop at 3.

Example 2

routes = [[2,5,9],[9,4,1],[1,8,3],[6,7]]source = 5target = 7return = -1

Stop 7 is only on bus 3, and bus 3 shares no stop with any other bus. You can never get on it from stop 5, so the answer is -1.

Example 3

routes = [[2,5,9]]source = 11target = 11return = 0

You are already at stop 11, so you need 0 buses. It does not matter that no bus stops there.

Constraints

  • 1 <= routes.length <= 500
  • 1 <= routes[i].length <= 10^4
  • The total number of stops in all routes is at most 10^4.
  • The stops in each routes[i] are all different.
  • 0 <= routes[i][j] < 10^6
  • 0 <= source, target < 10^6

More UiPath problems

  • Swim in Rising WaterPHONE SCREEN · Seen Nov 2026
  • New 21 Game ProbabilityPHONE SCREEN · Seen Sep 2026
  • Excel Sheet Column TitlePHONE SCREEN · Seen May 2026
See UiPath hiring insights
Saved
class Solution {
    public int numBusesToDestination(int[][] routes, int source, int target) {
        // Write your code here.
    }
}
Checking account…