{"id":11407,"date":"2025-12-25T13:05:22","date_gmt":"2025-12-25T07:35:22","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=11407"},"modified":"2025-12-31T17:01:32","modified_gmt":"2025-12-31T11:31:32","slug":"number-of-operations-to-make-network-connected","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/number-of-operations-to-make-network-connected\/","title":{"rendered":"Number of Operations to Make Network Connected"},"content":{"rendered":"\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n  <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n  <h1 class=\"wp_blog_main-heading\"><\/h1>\n\n  <div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n        There are n computers numbered from <code>0<\/code> to <code>n-1<\/code> connected by ethernet cables <code>connections<\/code> forming a network where <code>connections[i] = [a<sub>i<\/sub>, b<sub>i<\/sub>]<\/code> represents a connection between computers <code>a<sub>i<\/sub><\/code> and <code>b<sub>i<\/sub><\/code>. Any computer can reach any other computer directly or indirectly through the network.\n    <\/p>\n    <p>\n        You are given an initial computer network <code>connections<\/code>. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.\n    <\/p>\n    <p>\n        Return <i>the minimum number of times you need to do this in order to make all the computers connected<\/i>. If it is not possible, return <code>-1<\/code>.\n    <\/p>\n\n    <h3>Example 1:<\/h2>\n    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/12\/Screenshot-2025-12-25-at-12.29.40-PM.png\" alt=\"\">\n    <p><strong>Input:<\/strong> n = 4, connections = [[0,1],[0,2],[1,2]]<\/p>\n    <p><strong>Output:<\/strong> 1<\/p>\n    <p><strong>Explanation:<\/strong> Remove cable between computer 1 and 2 and place between computers 1 and 3.<\/p>\n\n    <h3>Example 2:<\/h2>\n    <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/12\/Screenshot-2025-12-25-at-12.30.00-PM.png\" alt=\"\">\n    <p><strong>Input:<\/strong> n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]<\/p>\n    <p><strong>Output:<\/strong> 2<\/p>\n\n    <h3>Example 3:<\/h2>\n    <p><strong>Input:<\/strong> n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]<\/p>\n    <p><strong>Output:<\/strong> -1<\/p>\n    <p><strong>Explanation:<\/strong> There are not enough cables.<\/p>\n\n    <h3>Constraints<\/h3>\n    <ul>\n       <li><code>1 <= n <= 10<sup>5<\/sup><\/code><\/li>\n       <li><code>1 <= connections.length <= min(n * (n - 1) \/ 2, 10<sup>5<\/sup>)<\/code><\/li>\n       <li><code>connections[i].length == 2<\/code><\/li>\n       <li><code>0 <= a<sub>i<\/sub>, b<sub>i<\/sub> < n<\/code><\/li>\n       <li><code>a<sub>i<\/sub> != b<sub>i<\/sub><\/code><\/li>\n       <li>There are no repeated connections.<\/li>\n       <li>No two computers are connected by more than one cable.<\/li>\n    <\/ul>\n    \n<h2>Approach:<\/h2>\n   <ul>\n    <li>To <strong>connect<\/strong> all <code>n<\/code> computers, at least n - 1 connections are required. If not, <code>return -1<\/code>.<\/li>\n    <li>Build an <code>undirected graph<\/code> using the given connections.<\/li>\n    <li>Use <strong>BFS to traverse the graph <\/strong>and count the number of connected components.<\/li>\n    <li>Each <strong>BFS<\/strong> call marks all nodes in one component as <strong>visited<\/strong>.<\/li>\n    <li>If there are k connected components, we need <code>k - 1 <\/code>extra connections to connect them all.<\/li>\n    <li>Return <code>noOfComponents - 1<\/code>.<\/li>\n   <\/ul>\n\n    <h2>Time & Space Complexity:<\/h2>\n    <p><strong>Time Complexity:<\/strong> <code>O(V + E)<\/code><\/p>\n    <p><strong>Space Complexity:<\/strong> <code>O(V + E)<\/code><\/p>\n\n<h2>Dry Run<\/h2> \n<div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> \n  <p><strong>Input:<\/strong> <code>n = 5<\/code>, <code>connections = [[0,1],[0,2],[3,4]]<\/code><\/p> \n  \n  <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\">\n\nStep 0: Start Function: makeConnected(5, connections)\n\nconnections.length = 3\nn - 1 = 4\nconnections.length < n - 1 \u2192 false (so continue)\n\nStep 1: Build Graph (Adjacency List)\n\ngraph = [\n  [1, 2],   \/\/ 0\n  [0],      \/\/ 1\n  [0],      \/\/ 2\n  [4],      \/\/ 3\n  [3]       \/\/ 4\n]\n\nvisited = [false, false, false, false, false]\nnoOfComponents = 0\n\nStep 2: Traverse Nodes (for loop)\n\ni = 0:\n- visited[0] = false\n- noOfComponents = 1\n- Call bfs(0)\n\nBFS starting from node 0:\nQueue = [0]\nvisited = [true, false, false, false, false]\n\nPop 0:\n- Neighbor 1 \u2192 mark visited, push to queue\n- Neighbor 2 \u2192 mark visited, push to queue\nQueue = [1, 2]\nvisited = [true, true, true, false, false]\n\nPop 1:\n- Neighbor 0 already visited\n\nPop 2:\n- Neighbor 0 already visited\n\nBFS ends for component starting at 0\n\ni = 1:\n- visited[1] = true \u2192 skip\n\ni = 2:\n- visited[2] = true \u2192 skip\n\ni = 3:\n- visited[3] = false\n- noOfComponents = 2\n- Call bfs(3)\n\nBFS starting from node 3:\nQueue = [3]\nvisited = [true, true, true, true, false]\n\nPop 3:\n- Neighbor 4 \u2192 mark visited, push to queue\nQueue = [4]\nvisited = [true, true, true, true, true]\n\nPop 4:\n- Neighbor 3 already visited\n\nBFS ends for component starting at 3\n\ni = 4:\n- visited[4] = true \u2192 skip\n\nStep 3: End\n\nTotal Components = 2\nRequired Operations = noOfComponents - 1 = 2 - 1 = 1\n  <\/pre> \n  \n  <p><strong>Output:<\/strong> <code>1<\/code><\/p> \n<\/div>\n\n\n        <!-- <h2>Visualisation:<\/h2>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/09\/4.png\" alt=\"\"> -->\n   \n<\/div>\n\n\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\nvar makeConnected = function(n, connections) {\n\n    if (connections.length < n - 1) return -1;\n    let graph = Array.from({ length: n }, () => []);\n    for (let [from, to] of connections) {\n        graph[from].push(to);\n        graph[to].push(from);\n    }\n\n    let visited = new Array(n).fill(false);\n    let noOfComponents = 0;\n\n    for (let i = 0; i < n; i++) {\n        if (!visited[i]) {\n            noOfComponents++;\n            bfs(i, visited, graph);\n        }\n    }\n\n    return noOfComponents - 1;\n};\n\nfunction bfs(src, visited, graph) {\n    let q = [src];\n    visited[src] = true;\n\n    while (q.length) {\n        let curr = q.shift();\n        for (let neighbor of graph[curr]) {\n            if (!visited[neighbor]) {\n                visited[neighbor] = true;\n                q.push(neighbor);\n            }\n        }\n    }\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\nfrom collections import deque\n\ndef makeConnected(n, connections):\n    if len(connections) < n - 1:\n        return -1\n\n    graph = [[] for _ in range(n)]\n    for u, v in connections:\n        graph[u].append(v)\n        graph[v].append(u)\n\n    visited = [False] * n\n    components = 0\n\n    def bfs(src):\n        q = deque([src])\n        visited[src] = True\n\n        while q:\n            curr = q.popleft()\n            for neighbor in graph[curr]:\n                if not visited[neighbor]:\n                    visited[neighbor] = True\n                    q.append(neighbor)\n\n    for i in range(n):\n        if not visited[i]:\n            components += 1\n            bfs(i)\n\n    return components - 1\n\n      <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\nimport java.util.*;\n\nclass Solution {\n    public int makeConnected(int n, int[][] connections) {\n        if (connections.length < n - 1) return -1;\n\n        List<List<Integer>> graph = new ArrayList<>();\n        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());\n\n        for (int[] edge : connections) {\n            graph.get(edge[0]).add(edge[1]);\n            graph.get(edge[1]).add(edge[0]);\n        }\n\n        boolean[] visited = new boolean[n];\n        int components = 0;\n\n        for (int i = 0; i < n; i++) {\n            if (!visited[i]) {\n                components++;\n                bfs(i, graph, visited);\n            }\n        }\n\n        return components - 1;\n    }\n\n    private void bfs(int src, List<List<Integer>> graph, boolean[] visited) {\n        Queue<Integer> q = new LinkedList<>();\n        q.add(src);\n        visited[src] = true;\n\n        while (!q.isEmpty()) {\n            int curr = q.poll();\n            for (int neighbor : graph.get(curr)) {\n                if (!visited[neighbor]) {\n                    visited[neighbor] = true;\n                    q.add(neighbor);\n                }\n            }\n        }\n    }\n}\n\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;\n#include &lt;queue&gt;\nusing namespace std;\n\nclass Solution {\npublic:\n    int makeConnected(int n, vector<vector<int>>& connections) {\n        if (connections.size() < n - 1) return -1;\n\n        vector<vector<int>> graph(n);\n        for (auto& edge : connections) {\n            graph[edge[0]].push_back(edge[1]);\n            graph[edge[1]].push_back(edge[0]);\n        }\n\n        vector<bool> visited(n, false);\n        int components = 0;\n\n        for (int i = 0; i < n; i++) {\n            if (!visited[i]) {\n                components++;\n                bfs(i, graph, visited);\n            }\n        }\n\n        return components - 1;\n    }\n\n    void bfs(int src, vector<vector<int>>& graph, vector<bool>& visited) {\n        queue<int> q;\n        q.push(src);\n        visited[src] = true;\n\n        while (!q.empty()) {\n            int curr = q.front();\n            q.pop();\n\n            for (int neighbor : graph[curr]) {\n                if (!visited[neighbor]) {\n                    visited[neighbor] = true;\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n};\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define MAX 100000\n\nint visited[MAX];\nint graph[MAX][MAX];\nint graphSize[MAX];\n\nvoid bfs(int src, int n) {\n    int queue[MAX], front = 0, rear = 0;\n    queue[rear++] = src;\n    visited[src] = 1;\n\n    while (front < rear) {\n        int curr = queue[front++];\n        for (int i = 0; i < graphSize[curr]; i++) {\n            int neighbor = graph[curr][i];\n            if (!visited[neighbor]) {\n                visited[neighbor] = 1;\n                queue[rear++] = neighbor;\n            }\n        }\n    }\n}\n\nint makeConnected(int n, int connections[][2], int size) {\n    if (size < n - 1) return -1;\n\n    for (int i = 0; i < n; i++) {\n        visited[i] = 0;\n        graphSize[i] = 0;\n    }\n\n    for (int i = 0; i < size; i++) {\n        int u = connections[i][0];\n        int v = connections[i][1];\n        graph[u][graphSize[u]++] = v;\n        graph[v][graphSize[v]++] = u;\n    }\n\n    int components = 0;\n    for (int i = 0; i < n; i++) {\n        if (!visited[i]) {\n            components++;\n            bfs(i, n);\n        }\n    }\n    return components - 1;\n}\n <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n    public int MakeConnected(int n, int[][] connections) {\n        if (connections.Length < n - 1) return -1;\n\n        List<int>[] graph = new List<int>[n];\n        for (int i = 0; i < n; i++) graph[i] = new List<int>();\n\n        foreach (var edge in connections) {\n            graph[edge[0]].Add(edge[1]);\n            graph[edge[1]].Add(edge[0]);\n        }\n\n        bool[] visited = new bool[n];\n        int components = 0;\n\n        for (int i = 0; i < n; i++) {\n            if (!visited[i]) {\n                components++;\n                BFS(i, graph, visited);\n            }\n        }\n\n        return components - 1;\n    }\n\n    private void BFS(int src, List<int>[] graph, bool[] visited) {\n        Queue<int> q = new Queue<int>();\n        q.Enqueue(src);\n        visited[src] = true;\n\n        while (q.Count > 0) {\n            int curr = q.Dequeue();\n            foreach (int neighbor in graph[curr]) {\n                if (!visited[neighbor]) {\n                    visited[neighbor] = true;\n                    q.Enqueue(neighbor);\n                }\n            }\n        }\n    }\n}\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,810,174,172,173],"tags":[],"class_list":["post-11407","post","type-post","status-publish","format-standard","category-algorithms","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11407","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=11407"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11407\/revisions"}],"predecessor-version":[{"id":11408,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11407\/revisions\/11408"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=11407"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=11407"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=11407"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}