In all languages, easy to understand, DFS only 
Please upvote ❤️IntuitionThe problem requires finding the minimum bitwise AND-cost for connected components in a graph. Since edges define connectivity, we firs
# Please upvote ❤️

## Intuition  
The problem requires finding the minimum bitwise **AND-cost** for connected components in a graph. Since edges define connectivity, we first determine which nodes belong to the same component. Once components are identified, we compute the minimum **AND-cost** for each.  

## Approach  
1. **Graph Representation:** Use an **adjacency list** to store edges.  
2. **Component Identification:** Use **DFS** to traverse and label connected components.  
3. **AND-Cost Calculation:** While traversing, maintain the minimum bitwise **AND** of edge weights for each component.  
4. **Query Processing:** If two nodes belong to the same component, return the precomputed **AND-cost**; otherwise, return `-1`.  

## Complexity  
- **Time Complexity:**  
  - Constructing the graph: $$O(E)$$  
  - DFS traversal: $$O(N + E)$$  
  - Query processing: $$O(Q)$$  
  - **Total:** $$O(N + E + Q)$$  

- **Space Complexity:**  
  - Adjacency list: $$O(N + E)$$  
  - Component mapping and costs: $$O(N)$$  
  - **Total:** $$O(N + E)$$  
# Code
```typescript []
let minimumCost = (N, E, query) => {
  let adj = [...Array(N)].map(_ => []),  // Adjacency List
    cost = new Map(),                 // Store min AND-cost per component
    color = 0,                         // Unique ID for each component
    group = [...Array(N)].map((_, i) => -(i + 1)), // Component mapping
    seen = [...Array(N)].map(_ => false);                  // Visited nodes

  // Build adjacency list
  for (let [u, v, w] of E) {
    adj[u].push([v, w]);
    adj[v].push([u, w]);
  }

  // DFS function to mark components & calculate AND-cost
  let go = (u, color) => {
    if (seen[u]) return;
    seen[u] = true, group[u] = color;
    for (let [v, w] of adj[u]) {
      go(v, color);
      cost.set(color, cost.has(color) ? cost.get(color) & w : w);
    }
  };

  // Identify components using DFS
  for (let i = 0; i < N; ++i) {
    if (!seen[i]) go(i, ++color);
  }

  // queries
  return query.map(([u, v]) => group[u] == group[v] ? cost.get(group[u]) : -1);
};
```
```javascript []
var minimumCost = function(N, E, query) {
    let adj = Array.from({ length: N }, () => []);
    let cost = new Map(), group = new Array(N).fill(-1), visited = new Array(N).fill(false);
    let color = 0;

    for (let [u, v, w] of E) {
        adj[u].push([v, w]);
        adj[v].push([u, w]);
    }

    const dfs = (node, id) => {
        if (visited[node]) return;
        visited[node] = true;
        group[node] = id;
        for (let [neighbor, weight] of adj[node]) {
            dfs(neighbor, id);
            cost.set(id, cost.has(id) ? cost.get(id) & weight : weight);
        }
    };

    for (let i = 0; i < N; i++) {
        if (!visited[i]) dfs(i, color++);
    }

    return query.map(([u, v]) => (group[u] === group[v]) ? cost.get(group[u]) ?? -1 : -1);
};
```

```cpp []
class Solution {
public:
    vector<int> minimumCost(int N, vector<vector<int>>& E, vector<vector<int>>& query) {
        vector<vector<pair<int, int>>> adj(N);
        vector<int> group(N, -1), res;
        unordered_map<int, int> cost;
        int color = 0;

        for (auto& edge : E) {
            int u = edge[0], v = edge[1], w = edge[2];
            adj[u].emplace_back(v, w);
            adj[v].emplace_back(u, w);
        }

        function<void(int, int)> dfs = [&](int node, int c) {
            if (group[node] != -1) return;
            group[node] = c;
            for (auto& [neighbor, weight] : adj[node]) {
                dfs(neighbor, c);
                cost[c] = cost.count(c) ? (cost[c] & weight) : weight;
            }
        };

        for (int i = 0; i < N; ++i)
            if (group[i] == -1) dfs(i, color++);

        for (auto& q : query)
            res.push_back(group[q[0]] == group[q[1]] ? cost[group[q[0]]] : -1);

        return res;
    }
};
```
```java []
class Solution {
    static ArrayList<Pair<Integer, Integer>> graph[];
    static boolean vis[];
    static int componentOfNode[];
    static ArrayList<Integer> componentValue;
    public static int dfsUtil(int node, int value, int bitwiseAND) {
        if(vis[node]) {
            return bitwiseAND;
        }

        componentOfNode[node] = value;
        vis[node] = true;
        for(Pair<Integer, Integer> x : graph[node]) {
            int neighbour = x.getKey();
            int weight = x.getValue();
            if(!vis[neighbour]) {
                bitwiseAND = dfsUtil(neighbour, value, bitwiseAND == -1 ? weight : bitwiseAND & weight);
            }
            bitwiseAND &= weight; //if same nodes have multiple edges
        }

        return bitwiseAND;
    }

    public static void dfs(int n) {
        vis = new boolean[n];
        componentOfNode = new int[n];
        componentValue = new ArrayList<>();
        int componentCount = 0;
        for(int i=0; i<n; ++i) {
            if(!vis[i]) {
                componentValue.add(componentCount, dfsUtil(i, componentCount, -1));
                ++componentCount;
            }
        }
    }

    public int[] minimumCost(int n, int[][] edges, int[][] query) {
        graph = new ArrayList[n];
        for(int i=0; i<n; ++i) {
            graph[i] = new ArrayList<>();
        }
        for(int e[] : edges) {
            graph[e[0]].add(new Pair(e[1], e[2]));
            graph[e[1]].add(new Pair(e[0], e[2]));
        }

        dfs(n);

        int m = query.length;
        int u = 0, v = 0;
        int res[] = new int[m];
        for(int i=0; i<m; ++i) {
            u = query[i][0];
            v = query[i][1];

            if(componentOfNode[u] != componentOfNode[v]) {
                res[i] = -1;
                continue;
            }

            res[i] = componentValue.get(componentOfNode[u]);
        }


        return res;
    }
}
```
``` python []
class Solution:
  def minimumCost(self, N, E, query):
      adj = defaultdict(list)
      cost = {}
      group = [-1] * N
      visited = [False] * N
      color = 0

      for u, v, w in E:
          adj[u].append((v, w))
          adj[v].append((u, w))

      def dfs(node, col):
          if visited[node]: return
          visited[node] = True
          group[node] = col
          for neighbor, weight in adj[node]:
              dfs(neighbor, col)
              cost[col] = cost.get(col, weight) & weight

      for i in range(N):
          if not visited[i]:
              dfs(i, color)
              color += 1

      return [cost[group[u]] if group[u] == group[v] else -1 for u, v in query]
```
``` csharp []
class Solution {
    public int[] MinimumCost(int N, int[][] E, int[][] query) {
        var adj = new List<(int, int)>[N];
        var cost = new Dictionary<int, int>();
        var group = new int[N];
        Array.Fill(group, -1);
        var visited = new bool[N];
        int color = 0;

        for (int i = 0; i < N; i++) adj[i] = new List<(int, int)>();
        foreach (var edge in E) {
            adj[edge[0]].Add((edge[1], edge[2]));
            adj[edge[1]].Add((edge[0], edge[2]));
        }

        void Dfs(int node, int c) {
            if (visited[node]) return;
            visited[node] = true;
            group[node] = c;
            foreach (var (neighbor, weight) in adj[node]) {
                Dfs(neighbor, c);
                if (!cost.ContainsKey(c)) cost[c] = weight;
                else cost[c] &= weight;
            }
        }

        for (int i = 0; i < N; i++) {
            if (!visited[i]) Dfs(i, color++);
        }

        var res = new int[query.Length];
        for (int i = 0; i < query.Length; i++) {
            res[i] = (group[query[i][0]] == group[query[i][1]]) ? cost[group[query[i][0]]] : -1;
        }
        return res;
    }
}
```
```golang []
func minimumCost(N int, E [][]int, query [][]int) []int {
    adj := make([][]struct{ v, w int }, N)
    group := make([]int, N)
    cost := make(map[int]int)
    visited := make([]bool, N)
    color := 0

    for i := range adj {
        adj[i] = []struct{ v, w int }{}
    }

    for _, e := range E {
        u, v, w := e[0], e[1], e[2]
        adj[u] = append(adj[u], struct{ v, w int }{v, w})
        adj[v] = append(adj[v], struct{ v, w int }{u, w})
    }

    var dfs func(int, int)
    dfs = func(node, c int) {
        if visited[node] {
            return
        }
        visited[node] = true
        group[node] = c
        for _, neighbor := range adj[node] {
            dfs(neighbor.v, c)
            if v, ok := cost[c]; ok {
                cost[c] = v & neighbor.w
            } else {
                cost[c] = neighbor.w
            }
        }
    }

    for i := 0; i < N; i++ {
        if !visited[i] {
            dfs(i, color)
            color++
        }
    }

    res := make([]int, len(query))
    for i, q := range query {
        if group[q[0]] == group[q[1]] {
            res[i] = cost[group[q[0]]]
        } else {
            res[i] = -1
        }
    }
    return res
}

```
``` swift []
class Solution {
  func minimumCost(_ N: Int, _ E: [[Int]], _ queries: [[Int]]) -> [Int] {
      var adj = [[(Int, Int)]](repeating: [], count: N)
      var cost = [Int: Int]()
      var group = [Int](repeating: -1, count: N)
      var visited = [Bool](repeating: false, count: N)
      var color = 0

      for edge in E {
          let (u, v, w) = (edge[0], edge[1], edge[2])
          adj[u].append((v, w))
          adj[v].append((u, w))
      }

      func dfs(_ node: Int, _ id: Int) {
          if visited[node] { return }
          visited[node] = true
          group[node] = id
          for (neighbor, weight) in adj[node] {
              dfs(neighbor, id)
              cost[id] = cost[id] == nil ? weight : (cost[id]! & weight)
          }
      }

      for i in 0..<N {
          if !visited[i] {
              dfs(i, color)
              color += 1
          }
      }

      return queries.map { q in
          let (u, v) = (q[0], q[1])
          return group[u] == group[v] ? (cost[group[u]] ?? -1) : -1
      }
  }
}
```
## Two cats for you 😻
![image.png](https://assets.leetcode.com/users/images/3c7f612b-0940-4bb7-b311-0782a853fe96_1742454090.5360854.png)
![image.png](https://assets.leetcode.com/users/images/3c7f612b-0940-4bb7-b311-0782a853fe96_1742454090.5360854.png)
['Array', 'Bit Manipulation', 'Swift', 'Python', 'C++', 'Java', 'Go', 'TypeScript', 'JavaScript', 'C#']