Checking Existence of Edge Length Limited Paths II Problem
Description
LeetCode Problem 1724.
An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [u_i, v_i, dis_i] denotes an edge between nodes u_i and v_i with distance dis_i. 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)Returnstrueif there exists a path fromptoqsuch that each edge on the path has a distance strictly less thanlimit, and otherwisefalse.
Example 1:

Input
["DistanceLimitedPathsExist", "query", "query", "query", "query"]
[[6, [[0, 2, 4], [0, 3, 2], [1, 2, 3], [2, 3, 1], [4, 5, 5]]], [2, 3, 2], [1, 3, 3], [2, 0, 3], [0, 5, 6]]
Output
[null, true, false, true, false]
Explanation
DistanceLimitedPathsExist distanceLimitedPathsExist = new DistanceLimitedPathsExist(6, [[0, 2, 4], [0, 3, 2], [1, 2, 3], [2, 3, 1], [4, 5, 5]]);
distanceLimitedPathsExist.query(2, 3, 2); // return true. There is an edge from 2 to 3 of distance 1, which is less than 2.
distanceLimitedPathsExist.query(1, 3, 3); // return false. There is no way to go from 1 to 3 with distances strictly less than 3.
distanceLimitedPathsExist.query(2, 0, 3); // return true. There is a way to go from 2 to 0 with distance < 3: travel from 2 to 3 to 0.
distanceLimitedPathsExist.query(0, 5, 6); // return false. There are no paths from 0 to 5.
**Constraints:**
2 <= n <= 10^40 <= edgeList.length <= 10^4edgeList[i].length == 30 <= u_i, v_i, p, q <= n-1u_i != v_ip != q1 <= dis_i, limit <= 10^9- At most
10^4calls will be made toquery.
Solution
Approach: Persistent Union-Find
Queries arrive online, so we cannot sort them together with the edges. Instead we build a union-find structure that remembers when each link was made.
Process the edges in increasing order of distance. Union by rank, without path compression, and when a root is attached under another one, store the edge distance in version for the attached root. The tree depth stays O(log n).
To answer query(p, q, limit), walk up from each node but follow a parent link only if its stored distance is strictly less than limit. The two walks end at the same root exactly when the nodes were already connected by edges shorter than limit.
Complexity: O(E log E) to build, then O(log n) per query, with O(n) space.
from math import inf
class PersistentUnionFind:
def __init__(self, n):
self.rank = [0] * n
self.p = list(range(n))
self.version = [inf] * n
def find(self, x, t=inf):
if self.p[x] == x or self.version[x] >= t:
return x
return self.find(self.p[x], t)
def union(self, a, b, t):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.rank[pa] > self.rank[pb]:
self.version[pb] = t
self.p[pb] = pa
else:
self.version[pa] = t
self.p[pa] = pb
if self.rank[pa] == self.rank[pb]:
self.rank[pb] += 1
return True
class DistanceLimitedPathsExist:
def __init__(self, n: int, edgeList: List[List[int]]):
self.puf = PersistentUnionFind(n)
edgeList.sort(key=lambda x: x[2])
for u, v, dis in edgeList:
self.puf.union(u, v, dis)
def query(self, p: int, q: int, limit: int) -> bool:
return self.puf.find(p, limit) == self.puf.find(q, limit)