Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Shortest Distance After Road Addition Queries I

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3243" 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 integer n and a 2D integer array queries. There are n cities numbered from 0 to n - 1. Initially, there is a unidirectional road from city i to city i + 1 for all 0 <= i < n - 1. queries[i] = [ui, vi] represents the addition of a new unidirectional road from city ui to city vi. After each query, you need to find the length of the shortest path from city 0 to city n - 1. Return an array answer where for each i in the range [0, queries.length - 1], answer[i] is the length of the shortest path from city 0 to city n - 1 after processing the first i + 1 queries. Example 1: Input: n = 5, queries = [[2,4],[0,2],[0,4]] Output: [3,2,1] Explanation: After the addition of the road from 2 to 4, the length of the shortest path from 0 to 4 is 3. After the addition of the road from 0 to 2, the length of the shortest path from 0 to 4 is 2. After the addition of the road from 0 to 4, the length of the shortest path from 0 to 4 is 1. Example 2: Input: n = 4, queries = [[0,3],[0,2]] Output: [1,1] Explanation: After the addition of the road from 0 to 3, the length of the shortest path from 0 to 3 is 1. After the addition of the road from 0 to 2, the length of the shortest path remains 1. Constraints: 3 <= n <= 500 1 <= queries.length <= 500 queries[i].length == 2 0 <= queries[i][0] < queries[i][1] < n 1 < queries[i][1] - queries[i][0] There are no repeated roads among the queries.

Explanation

Here's the solution approach:

  • Represent the graph: Maintain an adjacency matrix to represent the graph. Initially, populate it with the default edges (i to i+1).
  • Update and calculate shortest path: For each query, add the new edge to the adjacency matrix. Then, use the Floyd-Warshall algorithm to compute the shortest path between all pairs of nodes. The shortest path from 0 to n-1 is then simply the value at dist[0][n-1].
  • Store the results: Store the shortest path length after each query in the result array.

  • Runtime & Storage Complexity: The runtime complexity is O(q * n^3) due to the Floyd-Warshall algorithm being executed for each query, where 'q' is the number of queries and 'n' is the number of cities. The storage complexity is O(n^2) for the adjacency matrix.

Code

    def shortest_path_after_queries(n, queries):
    """
    Calculates the shortest path from city 0 to city n-1 after each query.

    Args:
        n: The number of cities.
        queries: A list of queries, where each query is a list [ui, vi].

    Returns:
        A list of the shortest path lengths after each query.
    """

    INF = float('inf')
    results = []

    # Initialize the distance matrix with default edges
    dist = [[INF] * n for _ in range(n)]
    for i in range(n):
        dist[i][i] = 0  # Distance from a node to itself is 0
        if i < n - 1:
            dist[i][i + 1] = 1  # Initial unidirectional roads

    for query in queries:
        u, v = query
        dist[u][v] = 1  # Add the new road

        # Floyd-Warshall Algorithm
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

        results.append(dist[0][n - 1])

        # Reset the dist matrix to initial state, except keep new roads for future queries

        temp_dist = [[INF] * n for _ in range(n)]
        for i in range(n):
            temp_dist[i][i] = 0
            if i < n - 1:
                temp_dist[i][i + 1] = 1

        for q in queries[:len(results)]: # keep the edges already added
            u,v = q
            temp_dist[u][v] = 1

        dist = temp_dist


        # Floyd-Warshall Algorithm after adding the new edge for future queries

        for k in range(n):
            for i in range(n):
                for j in range(n):
                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])


    return results

More from this blog

C

Chatmagic blog

2894 posts