Number of operations to make network connected

Graphs Hard Problems II Hard

Given a graph with n vertices and m edges. The graph is represented by an array Edges, where Edge[i] = [a, b] indicates an edge between vertices a and b. One edge can be removed from anywhere and added between any two vertices in one operation. Find the minimum number of operations that will be required to make the graph connected. If it is not possible to make the graph connected, return -1.

Examples:

Input : n = 4, Edge =[ [0, 1], [ 0, 2], [1, 2]]



Output: 1

Explanation: We need a minimum of 1 operation to make the two components connected. We can remove the edge (1,2) and add the edge between node 2 and node 3 like the following:


Input: n = 9, Edge = [[0,1],[0,2],[0,3],[1,2],[2,3],[4,5],[5,6],[7,8]]



Output: 2

Explanation: We need a minimum of 2 operations to make the two components connected. We can remove the edge (0,2) and add the edge between node 3 and node 4 and we can remove the edge (0,3) and add it between nodes 6 and 8 like the following:


Input: n = 4, Edge =[[0, 1]]

Constraints

  •   1 <= n <= 104
  •   1 <= Edge.length <= 104
  •   Edge[i].length == 2

Hints

  • "The problem can be solved using Disjoint Set Union (DSU) / Union-Find: Find the number of connected components. If we have c components, at least c-1 edge moves are needed to connect them."
  • "Initialize a Union-Find data structure for n nodes. Union all edges and track the number of connected components. Count the number of extra edges that can be moved. If the number of extra edges is at least c-1, return c-1; otherwise, return -1."

Company Tags

Cerner Visa IBM Riot Games Bloomberg Boston Consulting Group MongoDB Docker AMD Wayfair JPMorgan Chase PayPal eBay Western Digital Micron Technology Shopify Dropbox GE Healthcare Teladoc Health Freshworks KPMG ARM Robinhood Instacart Databricks Google Microsoft Amazon Meta Apple Netflix Adobe