#815

Bus Routes

Hard
ArrayHash TableBreadth-First SearchHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a breadth-first search (BFS) approach to explore bus routes efficiently. By treating bus stops as nodes and buses as edges, we can find the shortest path in terms of bus transfers.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a mapping of bus stops to the buses that serve them.
  2. 2Step 2: Initialize a queue for BFS starting from the source stop.
  3. 3Step 3: Track visited stops and buses to avoid cycles.
  4. 4Step 4: For each stop, explore all buses that can be taken and enqueue the next stops.
  5. 5Step 5: If the target stop is reached, return the number of buses taken.
solution.py32 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def numBusesToDestination(routes, source, target):
5    if source == target:
6        return 0
7
8    stop_to_buses = defaultdict(list)
9    for bus, stops in enumerate(routes):
10        for stop in stops:
11            stop_to_buses[stop].append(bus)
12
13    visited_stops = set()
14    visited_buses = set()
15    queue = deque([(source, 0)])  # (current stop, bus count)
16
17    while queue:
18        current_stop, bus_count = queue.popleft()
19        if current_stop in visited_stops:
20            continue
21        visited_stops.add(current_stop)
22
23        for bus in stop_to_buses[current_stop]:
24            if bus in visited_buses:
25                continue
26            visited_buses.add(bus)
27            for next_stop in routes[bus]:
28                if next_stop == target:
29                    return bus_count + 1
30                queue.append((next_stop, bus_count + 1))
31
32    return -1

Complexity note: The time complexity is linear because we are processing each bus stop and bus exactly once, making it efficient for large inputs.

  • 1Understanding how to map bus stops to the buses that serve them is crucial for efficient traversal.
  • 2Using BFS allows us to find the shortest path in terms of bus transfers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.