Python [union-find]
Sort E.\nSort Q but only get indices.\nGradually add edges in sorted E based on sorted Q.\nCheck if the given query nodes are connected.\nEssentially union-find
Sort `E`.\nSort `Q` but only get indices.\nGradually add edges in sorted `E` based on sorted `Q`.\nCheck if the given query nodes are connected.\nEssentially union-find.\n\n```python\nclass Solution:\n    def distanceLimitedPathsExist(self, n, E, Q):\n        #this part is union-find\n        def find(i):\n            if i != root[i]:\n                root[i] = find(root[i])\n            return root[i]\n\n        def uni(x, y):\n            x, y = find(x), find(y)\n            if x == y: return 0\n            root[x] = y\n            return 1\n        \n        root = list(range(n))\n        \n        #this will be the answer\n        ans = [False]*len(Q)\n        \n        #sort edges based on cost\n        i = 0\n        E.sort(key=lambda x: x[2])\n        \n        #don\'t sort Q, but get the sorted list of queries in ix_all\n        q = [x[2] for x in Q]\n        ix_all = sorted(range(len(q)), key=q.__getitem__)\n        for ix in ix_all: #loop over sorted indices of Q\n            #add all edges that satisfy cost requirement\n            while i<len(E) and E[i][2]<Q[ix][2]:\n                x, y = E[i][0], E[i][1]\n                i += 1\n                uni(x,y)\n            \n            #check if the query nodes are connected\n            if find(Q[ix][0]) == find(Q[ix][1]):\n                ans[ix] = True\n        \n        return ans\n```
[]