Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Cost Walk in Weighted Graph

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3108" 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

There is an undirected weighted graph with n vertices labeled from 0 to n - 1. You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi. A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once. The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator. You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1. Return the array answer, where answer[i] denotes the minimum cost of a walk for query i. Example 1: Input: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]] Output: [1,-1] Explanation: To achieve the cost of 1 in the first query, we need to move on the following edges: 0->1 (weight 7), 1->2 (weight 1), 2->1 (weight 1), 1->3 (weight 7). In the second query, there is no walk between nodes 3 and 4, so the answer is -1. Example 2: Input: n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]] Output: [0] Explanation: To achieve the cost of 0 in the first query, we need to move on the following edges: 1->2 (weight 1), 2->1 (weight 6), 1->2 (weight 1). Constraints: 2 <= n <= 105 0 <= edges.length <= 105 edges[i].length == 3 0 <= ui, vi <= n - 1 ui != vi 0 <= wi <= 105 1 <= query.length <= 105 query[i].length == 2 0 <= si, ti <= n - 1 si != ti

Explanation

  • Iterate through possible costs: The core idea is to iterate through all possible costs (from 0 to the maximum edge weight) in decreasing order. For each cost, determine if a path exists between the source and target nodes where all edge weights along the path have a bitwise AND value greater than or equal to the current cost.
    • Graph Traversal (e.g., DFS or BFS): For each possible cost, perform a graph traversal (either Depth-First Search or Breadth-First Search) to check if a path exists. The traversal only considers edges whose weights are greater than or equal to the current cost.
    • Optimization: By iterating in decreasing order of cost, we can return the first cost for which a path is found. This is because we are looking for the minimum cost, and starting from the highest possible cost allows us to find it faster.
  • Runtime Complexity: O(Q W (V + E)), where Q is the number of queries, W is the maximum edge weight, V is the number of vertices, and E is the number of edges. Storage Complexity: O(V + E).

Code

    from collections import defaultdict, deque

def solve():
    n, edges, queries = int(input()), [], []
    num_edges = int(input())
    for _ in range(num_edges):
        edges.append(list(map(int, input().split())))
    num_queries = int(input())
    for _ in range(num_queries):
        queries.append(list(map(int, input().split())))

    def find_min_cost(n, edges, queries):
        adj = defaultdict(list)
        max_weight = 0
        for u, v, w in edges:
            adj[u].append((v, w))
            adj[v].append((u, w))
            max_weight = max(max_weight, w)

        def has_path(start, end, cost):
            q = deque([start])
            visited = {start}

            while q:
                u = q.popleft()
                if u == end:
                    return True

                for v, w in adj[u]:
                    if w >= cost and v not in visited:
                        q.append(v)
                        visited.add(v)
            return False

        result = []
        for start, end in queries:
            min_cost = -1
            for cost in range(max_weight, -1, -1):
                valid_edges = [(u, v, w) for u, v, w in edges if w >= cost]

                temp_adj = defaultdict(list)
                for u,v,w in edges:
                  if w >= cost:
                    temp_adj[u].append((v,w))
                    temp_adj[v].append((u,w))




                if has_path(start, end, cost):
                    min_cost = cost
                    break
            result.append(min_cost)
        return result

    print(find_min_cost(n, edges, queries))

# Example usage (replace with actual input reading):
# n = 5
# edges = [[0, 1, 7], [1, 3, 7], [1, 2, 1]]
# queries = [[0, 3], [3, 4]]
# print(find_min_cost(n, edges, queries))

# n = 3
# edges = [[0, 2, 7], [0, 1, 15], [1, 2, 6], [1, 2, 1]]
# queries = [[1, 2]]
# print(find_min_cost(n, edges, queries))

# You can uncomment the following lines to run the function based on user input:
# solve()

More from this blog

C

Chatmagic blog

2894 posts