The naive approach of running a fresh BFS per query will time out.
Sort the edges by weight and process queries offline in increasing order of weight limit, using a Union-Find (Disjoint Set Union) data structure to incrementally add edges that satisfy the weight constraint. For each query, after adding all edges with weight < limit, check if the two nodes are in the same connected component. This yields near-linear time complexity.
Pro tip: Mention that offline processing with sorting and DSU is optimal for this problem, and briefly compare it to online approaches like binary search on a minimum spanning tree or Kruskal reconstruction tree, showing awareness of trade-offs.
Clarify that edges with weight strictly less than the limit are allowed, and that queries are independent. Discuss input size to choose an efficient algorithm.
Select Union-Find (Disjoint Set Union) with path compression and union by rank/size to efficiently maintain connected components as edges are added.
Sort edges by weight and queries by weight limit. Iterate through queries in increasing limit order, adding all edges with weight < limit to the DSU.
For each query, after adding the eligible edges, check if the two nodes belong to the same component using find operations.
State time complexity O((E + Q) log E) due to sorting, and space O(V + E). Handle cases like no edges, disconnected nodes, and equal weights.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.