[Java] Union-Find Solution
The trick is to sort the queries as well so that we could reuse the roots array.\n\nclass Solution {\n    \n    int curr = 0;\n    \n    public boolean[] distan
The trick is to sort the queries as well so that we could reuse the `roots` array.\n```\nclass Solution {\n    \n    int curr = 0;\n    \n    public boolean[] distanceLimitedPathsExist(int n, int[][] edges, int[][] queries) {\n        Arrays.sort(edges, (a, b) -> (a[2] - b[2]));\n\t\t// Add another column to the queries so that we know the index after sorting.\n        int[][] qs = new int[queries.length][4];\n        for(int i = 0; i < queries.length; i++) {\n            qs[i] = new int[]{queries[i][0], queries[i][1], queries[i][2], i};\n        }\n        Arrays.sort(qs, (a, b) -> (a[2] - b[2]));\n        boolean[] res = new boolean[queries.length];\n        int[] roots = new int[n];\n        for(int i = 0; i < n; i++) roots[i] = i;\n        for(int i = 0; i < queries.length; i++) {\n            int[] q = qs[i];\n            res[q[3]] = helper(edges, q[0], q[1], q[2], roots);\n        }\n        return res;\n    }\n    \n    private boolean helper(int[][] edges, int start, int end, int limit, int[] roots) {\n        for(int i = curr; i < edges.length; i++) {\n            int[] e = edges[i];\n            if(e[2] >= limit) {\n\t\t\t\t// \'curr\' is to mark until which step have we finished the union-find.\n                curr = i;\n                break;\n            }\n            int root1 = find(roots, e[0]);\n            int root2 = find(roots, e[1]);\n            if(root1 != root2) {\n                roots[root1] = root2;\n            }\n        }\n        return find(roots, start) == find(roots, end);\n    }\n    \n    private int find(int[] roots, int i) {\n        int j = i;\n        while(roots[i] != i) {\n            i = roots[i];\n        }\n        roots[j] = i;\n        return i;\n    }\n}\n```
['Java']