TikTok Interview Coding Question: Minimum HCV Transfers Between Source and Destination Stops

14 Views
No Comments

We have Uber HCV (High Capacity Vehicles) plying on the same routes in loops. Every route has a certain number of stops. The routes are represented as a 2D array, where each route[i] shows the route that the i-th HCV takes. For example, the 1st HCV route would be 1 -> 2 -> 7 -> 1 -> 2 -> 7 ... and so on. Find the minimum number of HCV transfers needed given a source and a destination stop.

Example 1:

Input: HCV routes: [[1, 2, 7], [3, 6, 7]], Source: 1, Destination: 7
Output: 0
(get into the first HCV on stop 1 and get down at stop 7, no hops needed)
Source: 1, Destination: 6
Output: 1
(get into the first HCV on stop 1, transfer on stop 7 to the next HCV and then get down at stop 6 from the other HCV, hence it needed 1 hop)

Return -1 if it’s unable to reach the destination from the given source.

Example 2:

HCV routes: [[1,2,3,4,5,6,7,8,9,10], [2,7]]
Source: 1, Destination: 7
Output: 0

This is a minimum-transfers problem on circular transit routes. Each HCV route can be modeled as a loop, and the goal is to reach the destination from the source with the fewest route changes. If source and destination lie on the same route, the answer is 0; otherwise, a transfer must happen at a shared stop. A standard solution is to map each stop to the routes that contain it, then run BFS over routes starting from all routes that include the source. Each BFS level represents one transfer. As soon as a route containing the destination is reached, that level is the answer; if no such route is reachable, return -1.

END
 0