Problem
An undirected graph of n
nodes is defined by edgeList
, where edgeList[i] = [ui, vi, disi]
denotes an edge between nodes ui
and vi
with distance disi
. Note that there may be multiple edges between two nodes, and the graph may not be connected.
Implement the DistanceLimitedPathsExist
class:
DistanceLimitedPathsExist(int n, int[][] edgeList)
Initializes the class with an undirected graph.boolean query(int p, int q, int limit)
Returnstrue
if there exists a path fromp
toq
such that each edge on the path has a distance strictly less thanlimit
, and otherwisefalse
.
Examples
Example 1:
|
|
Constraints:
2 <= n <= 10^4
0 <= edgeList.length <= 10^4
edgeList[i].length == 3
0 <= ui, vi, p, q <= n-1
ui != vi
p != q
1 <= disi, limit <= 10^9
- At most
104
calls will be made toquery
.
Solution
Method 1 – Offline Union-Find with Query Sorting
Intuition
For each query, we want to know if there is a path between two nodes such that all edge weights are strictly less than a given limit. By sorting both the edges and the queries by weight/limit, we can use a union-find (DSU) structure to incrementally connect nodes as the limit increases, efficiently answering all queries.
Reasoning
By processing queries in order of increasing limit, and always adding all edges with weight less than the current limit to the union-find, we ensure that at each query, the union-find structure represents the connectivity for all edges with weight less than the limit. Thus, we can answer each query in nearly constant time after sorting.
Approach
- Store all edges and queries, and sort both by edge weight and query limit, respectively.
- Use a union-find (DSU) structure to keep track of connected components.
- For each query (in order of increasing limit):
- Add all edges with weight less than the query’s limit to the union-find.
- Check if the two nodes in the query are connected in the union-find.
- Return the answer for each query.
Edge cases:
- No edges: only nodes themselves are connected.
- Multiple edges between nodes: only the smallest matters for each limit.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O((E + Q) * α(N))
, whereE
is the number of edges,Q
is the number of queries, andα
is the inverse Ackermann function (nearly constant), as each union/find operation is nearly constant time. - 🧺 Space complexity:
O(N + E)
, as we store the union-find structure and all edges.