Delivery Route Exists - Problem

A logistics company operates n warehouses numbered from 0 to n - 1.

You are given a 2D array roads where roads[i] = [u, v] means a delivery truck can travel in both directions between warehouse u and warehouse v.

Given two integers source and destination, return true if a delivery truck can reach the destination warehouse from the source warehouse, or false otherwise.

Input & Output

Example 1 — No Route
$ Input: n = 6, roads = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
💡 Note: Warehouses 0,1,2 form one network. Warehouses 3,4,5 form another. No route connects them.
Example 2 — Route Exists
$ Input: n = 3, roads = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
💡 Note: All warehouses connected. Route: 0→1→2 or 0→2.
Example 3 — Same Warehouse
$ Input: n = 1, roads = [], source = 0, destination = 0
Output: true
💡 Note: Source equals destination.

Constraints

  • 1 ≤ n ≤ 2 × 10^5
  • 0 ≤ roads.length ≤ 2 × 10^5
  • 0 ≤ u, v < n
  • 0 ≤ source, destination < n

Visualization

Tap to expand
Delivery Route Exists INPUT Warehouses: n = 6 Network A 0 1 2 Network B 3 4 5 source = 0 destination = 5 Can the delivery truck reach warehouse 5 from 0? ALGORITHM STEPS 1 Build Road Map Adjacency list from roads 2 BFS from Source Queue: [0], Visited: {0} 3 Explore Roads Visit connected warehouses 4 Check Destination Was warehouse 5 reached? Execution Trace: step dequeue visit queue init — 0 [0] 1 0 1,2 [1,2] 2 1 — [2] 3 2 — [] Warehouse 5 never reached! FINAL RESULT Network Analysis: 🚛 Network A: {0,1,2} source warehouse 0 is here 📦 Network B: {3,4,5} destination warehouse 5 is here No road connects the networks! Output: false 💡 Key Insight: A delivery route exists if and only if both warehouses are in the same connected road network. BFS explores from source in O(V+E). Union-Find checks connectivity in near O(1) per query. TutorialsPoint - Delivery Route Exists | BFS Traversal Approach
Asked in
Amazon 0 Google 0
4 Views
High Frequency
~15 min Avg. Time
0 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen