Problem Description
Given an undirected graph with n nodes represented by edgeList, where each edge is given in the form [u, v, weight], determine for each query [p, q, limit] whether there exists a path from node p to q such that every edge on the path has a weight strictly less than limit. Note that there may be multiple edges between the same pair of nodes.
Key Insights
- Sort both the edgeList and the queries by the weight and limit respectively.
- Use a Union Find (Disjoint Set Union) data structure to efficiently connect nodes.
- Process queries offline: while increasing the limit, add all edges from the sorted edgeList with weight less than the current query limit. Then check connectivity.
- Handling multiple queries and edges in a single sweep ensures efficiency.
Space and Time Complexity
Time Complexity: O(E log E + Q log Q + (E + Q) * α(n))
Space Complexity: O(n + E + Q)
(Note: α(n) is the inverse Ackermann function which is almost constant.)
Solution
We solve the problem by first sorting the edgeList based on the edge weights and the queries based on their limit. We then iterate through the queries in increasing order of limit. For each query, we union all edges from the sorted edgeList that have weights strictly less than the query's limit. After processing the appropriate edges, we check if the two nodes in the query belong to the same connected component by using the Union Find data structure. This approach is efficient given the constraints and allows us to answer each query in nearly constant time after sorting.