Minimum Cost Walk in Weighted Graph - Problem

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.

Input & Output

Example 1 — Basic Connected Graph
$ Input: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,0],[0,2]]
Output: [1,1,1]
💡 Note: Nodes 0,1,2,3 are connected. The minimum cost between any two is the AND of all edge weights: 7 & 7 & 1 = 1. Node 4 is isolated.
Example 2 — Multiple Components
$ Input: n = 3, edges = [[0,1,15],[1,2,6]], query = [[0,2]]
Output: [6]
💡 Note: All nodes are connected in one component. Minimum cost is 15 & 6 = 6.
Example 3 — No Path Exists
$ Input: n = 3, edges = [[0,1,4]], query = [[0,2]]
Output: [-1]
💡 Note: Node 2 is isolated from nodes 0 and 1, so no path exists.

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 105
  • edges[i].length == 3
  • 0 ≤ ui, vi ≤ n - 1
  • ui ≠ vi
  • 0 ≤ wi ≤ 105
  • 1 ≤ query.length ≤ 104
  • query[i].length == 2
  • 0 ≤ si, ti ≤ n - 1

Visualization

Tap to expand
Minimum Cost Walk: Find Paths with Bitwise ANDStep 1: Input012731Step 2: Components012ConnectedStep 3: Min CostCost = 7 & 3 & 1= 1Answer: 1Query [0,2]: Minimum cost walk = 1All paths in connected component have same minimum cost
Understanding the Visualization
1
Input Graph
Weighted undirected graph with n vertices and edges
2
Connected Components
Group vertices that can reach each other
3
Minimum Cost
Bitwise AND of all edges in component
Key Takeaway
🎯 Key Insight: Since walks can repeat edges, the minimum cost between any two nodes in a connected component is the bitwise AND of ALL edge weights in that component
Asked in
Google 35 Meta 28 Amazon 22
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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