💡Swift - Optimal Solution - Union Find
SolutionComplexity
Time: O(e+v+n)
Space: O(v)
# Solution
```swift
class Solution {
    func minimumCost(_ n: Int, _ edges: [[Int]], _ query: [[Int]]) -> [Int] {
        let unionFind = UnionFind(n: n)
        for edge in edges {
            unionFind.union(edge[0], edge[1])
        }

        var groupCost = Array(repeating: Int.max, count: n)
        for edge in edges {
            let group = unionFind.parent(edge[0])
            groupCost[group] = groupCost[group] & edge[2]
        }

        return query.map {
            let (x, y) = ($0[0], $0[1])
            let groupX = unionFind.parent(x)
            let groupY = unionFind.parent(y)
            if groupX == groupY {
                return groupCost[groupX]
            } else {
                return -1
            }
        }
    }
}

class UnionFind {

    var parent: [Int]
    var rank: [Int]

    init(n: Int) {
        parent = Array(0..<n)
        rank = Array(repeating: 0, count: n)
    }

    func union(_ x: Int, _ y: Int) {
        let parentX = parent(x)
        let parentY = parent(y)
        guard parentX != parentY else {
            return
        }

        let rankX = rank[parentX]
        let rankY = rank[parentY]
        if rankX == rankY {
            rank[parentX] += 1
            parent[parentY] = parentX
        } else if rankX > rankY {
            parent[parentY] = parentX
        } else {
            parent[parentX] = parentY
        }
    }

    func parent(_ node: Int) -> Int {
        var node = node
        while parent[node] != node {
            node = parent[node]
        }
        return node
    }
}
```
# Complexity
- Time: $$O(e + v + n)$$
- Space: $$O(v)$$
['Union Find', 'Swift']