Number of Operations to Make Network Connected

Number of Operations to Make Network Connected

Leetcode Daily Challenge (23rd March, 2023)

Problem Statement:-

There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a<sub>i</sub>, b<sub>i</sub>] represents a connection between computers a<sub>i</sub> and b<sub>i</sub>. Any computer can reach any other computer directly or indirectly through the network.

You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.

Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.

Link: https://leetcode.com/problems/number-of-operations-to-make-network-connected/

Problem Explanation with examples:-

Example 1

Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.

Example 2

Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
Explanation: There are 3 connected components [0, 1, 2, 3], [4] and [5]. We need at least 2 connections to make all nodes connect. So return 2.

Example 3

Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.

Constraints

  • 1 <= n <= 10<sup>5</sup>

  • 1 <= connections.length <= min(n * (n - 1) / 2, 10<sup>5</sup>)

  • connections[i].length == 2

  • 0 <= a<sub>i</sub>, b<sub>i</sub> < n

  • a<sub>i</sub> != b<sub>i</sub>

  • There are no repeated connections.

  • No two computers are connected by more than one cable.

Intuition:-

  • We need to find the number of connected components in the graph.

  • We can use DFS to find the number of connected components.

  • A graph can be represented as an adjacency list.

  • We can use a visited array to keep track of the visited nodes.

  • We can start with node 0 and call the dfs function.

  • We can iterate through all the adjacent nodes of the current node.

  • If the adjacent node is not visited, then we can call the dfs function on the adjacent node.

  • We can return 1 if the current node is not visited.

  • Finally, we can return the number of connected components in the graph.

  • We can also use BFS to find the number of connected components.

Solution:-

  • If the number of edges is less than n-1, then we can return -1 as we need at least n-1 edges to connect n nodes.

  • Initialize a graph to store the edges and weights of the graph.

  • Iterate through the edges and add the edges and weights to the graph.

  • Initialize a visited array to keep track of the visited nodes and set all the elements to 0.

  • Define a dfs function to find the number of connected components.

  • If the current node is visited, then we can return 0.

  • Set the current node to visited.

  • Iterate through all the adjacent nodes of the current node.

  • If the adjacent node is not visited, then we can call the dfs function on the adjacent node.

  • Return 1 if the current node is not visited.

  • Finally, we can return the number of connected components in the graph - 1 as we need to connect n nodes.

Code:-

JAVA Solution

class Solution {
    public int makeConnected(int n, int[][] connections) {
        if (connections.length < n-1) {
            return -1;
        }

        Set<Integer>[] graph = new Set[n];

        for (int i = 0; i < n; i++) {
            graph[i] = new HashSet<>();
        }

        for (int[] connection : connections) {
            int i = connection[0];
            int j = connection[1];
            graph[i].add(j);
            graph[j].add(i);
        }

        int[] visited = new int[n];

        int count = 0;
        for (int node = 0; node < n; node++) {
            if (visited[node] == 0) {
                dfs(node, visited, graph);
                count++;
            }
        }

        return count - 1;
    }

    private void dfs(int node, int[] visited, Set<Integer>[] graph) {
        visited[node] = 1;
        for (int neighbor : graph[node]) {
            if (visited[neighbor] == 0) {
                dfs(neighbor, visited, graph);
            }
        }
    }
}

Python Solution

class Solution:
    def makeConnected(self, n: int, connections: List[List[int]]) -> int:
        if len(connections) < n-1:
            return -1

        graph = [set() for i in range(n)]

        for i,j in connections:
            graph[i].add(j)
            graph[j].add(i)

        visited = [0] * n

        def dfs(node):
            if visited[node]:
                return 0

            visited[node] = 1
            for neighbor in graph[node]:
                dfs(neighbor)
            return 1

        return sum(dfs(node) for node in range(n)) - 1

Complexity Analysis:-

TIME:-

Time complexity is O(N+M), where n is the number of nodes and m is the number of edges in the graph. This is because we are performing a DFS traversal on the graph, which takes O(n+m) time.

SPACE:-

Space complexity is O(N+M). We are using an adjacency list to represent the graph, which takes O(n+m) space. We are also using an array to keep track of visited nodes, which takes O(n) space. Finally, the recursive call stack for the DFS traversal can have a maximum depth of n, so it also takes O(n) space.

References:-

Connect with me:-

Did you find this article valuable?

Support Leeting-LCS by becoming a sponsor. Any amount is appreciated!