Minimum Cost Walk in Weighted Graph - Union Find [JS]
Description Solution: Union Find It's optimal to visit as many edges as possible to lower the total bitwise AND. Because we can visit nodes and edges more than once, nodes within the same connected component can take the total bitwise AND of ALL edges within that connected component. Any pair of nodes within the same connected component will have the same cost. Use union find to get the connected groups and find the bitwise AND cost for the group. Note: If the two nodes of the query are equal, the answer is 0 because we are already at the target. n = number of nodes , m = number of edges , k = number of queries Time Complexity: O(n + m + q) Space Complexity: O(n + m + q) var minimumCost = function ( n, edges, query ) { let uf = new UnionFind(n), weights = Array (n).fill(- 1 ); for ( let [u, v, weight] of edges) { uf.union(u, v); weights[u] = weights[u] === - 1 ? weight : weights[u] & weight; // only need to keep track of edges from u...