Posts

Showing posts with the label Union Find

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...

Make Lexicographically Smallest Array by Swapping Elements - Grouping & Union Find [JS]

Description   Solution 1: Group Connected Indices Think of indices  (i, j)  where  Math.abs(nums[i] - nums[j]) <= limit , as an edge in a graph. A group of indices that are connected to each other by these edges can be sorted in any way. Group indices into connected groups. Sort  nums  in asc order, split  nums  into groups where each adjacent pair has a  difference <= limit . For each group, sort both indices and values in asc order. Assign the new value in sorted order to each index. n = length of nums Time Complexity:  O(n log(n)) Space Complexity:  O(n) var lexicographicallySmallestArray = function ( nums, limit ) { let n = nums.length, sorted = nums.map( ( num, idx ) => [num, idx]).sort( ( a, b ) => a[ 0 ] - b[ 0 ]); let groups = [], indices = []; for ( let i = 0 ; i <= n; i++) { if (i === 0 || i === n || sorted[i][ 0 ] - sorted[i - 1 ][ 0 ] > limit) { groups.push(indices); if (...