Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Bus Routes

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "815" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible. Example 1: Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Example 2: Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 Output: -1 Constraints: 1 <= routes.length <= 500. 1 <= routes[i].length <= 105 All the values of routes[i] are unique. sum(routes[i].length) <= 105 0 <= routes[i][j] < 106 0 <= source, target < 106

Explanation

Here's the solution to the bus routes problem, with explanations and code:

  • High-Level Approach:

    • Build a graph where nodes are buses, and an edge exists between two buses if they share a common bus stop.
    • Use Breadth-First Search (BFS) to find the shortest path (minimum number of buses) from the buses serving the source to the buses serving the target.
    • Handle edge cases where source and target are the same or unreachable.
  • Complexity:

    • Runtime: O(R*S + R^2), where R is the number of routes and S is the average number of stops per route. The R*S part is for building the stop-to-route mapping. The R^2 part is for building the bus-to-bus graph. The BFS takes O(R + E) which in our case translates to O(R^2).
    • Storage: O(R*S + R^2), where R is the number of routes and S is the average number of stops per route. Stop to route mapping is O(R*S). The bus to bus adjacency list is O(R^2). BFS queue size is O(R).

Code

    from collections import defaultdict, deque

def numBusesToDestination(routes, source, target):
    if source == target:
        return 0

    # Build stop-to-routes mapping
    stop_routes = defaultdict(list)
    for i, route in enumerate(routes):
        for stop in route:
            stop_routes[stop].append(i)

    # Find initial buses (those serving the source)
    initial_buses = stop_routes[source]
    if not initial_buses:
        return -1

    # Build bus-to-bus graph (adjacency list)
    bus_graph = defaultdict(list)
    for i in range(len(routes)):
        for j in range(i + 1, len(routes)):
            if any(stop in routes[i] for stop in routes[j]):
                bus_graph[i].append(j)
                bus_graph[j].append(i)

    # BFS to find shortest path
    queue = deque([(bus, 1) for bus in initial_buses]) # (bus, num_buses)
    visited = set(initial_buses)

    while queue:
        bus, num_buses = queue.popleft()

        # Check if this bus serves the target
        if target in routes[bus]:
            return num_buses

        # Explore adjacent buses
        for next_bus in bus_graph[bus]:
            if next_bus not in visited:
                visited.add(next_bus)
                queue.append((next_bus, num_buses + 1))

    return -1

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Bus Routes