- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 54 lines of Python from the credited upstream file checking-existence-of-edge-length-limited-paths.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class UnionFind(object): 5 def __init__(self, n):6 self.set = range(n)7 self.rank = [0]*n8 9 def find_set(self, x):10 stk = []11 while self.set[x] != x: 12 stk.append(x)13 x = self.set[x]14 while stk:15 self.set[stk.pop()] = x16 return x17 18 def union_set(self, x, y):19 x_root, y_root = map(self.find_set, (x, y))20 if x_root == y_root:21 return False22 if self.rank[x_root] < self.rank[y_root]: 23 self.set[x_root] = y_root24 elif self.rank[x_root] > self.rank[y_root]:25 self.set[y_root] = x_root26 else:27 self.set[y_root] = x_root28 self.rank[x_root] += 129 return True30 31 32class Solution(object):33 def distanceLimitedPathsExist(self, n, edgeList, queries):34 """35 :type n: int36 :type edgeList: List[List[int]]37 :type queries: List[List[int]]38 :rtype: List[bool]39 """40 for i, q in enumerate(queries):41 q.append(i)42 edgeList.sort(key=lambda x: x[2])43 queries.sort(key=lambda x: x[2])44 45 union_find = UnionFind(n)46 result = [False]*len(queries)47 curr = 048 for u, v, w, i in queries: 49 while curr < len(edgeList) and edgeList[curr][2] < w: 50 union_find.union_set(edgeList[curr][0], edgeList[curr][1])51 curr += 152 result[i] = union_find.find_set(u) == union_find.find_set(v)53 return result 54