FastPrepMinimum Edge Moves to Connect a Network

Minimum Edge Moves to Connect a Network

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You manage an undirected network with nodes 0 through n - 1. In one move, you may remove one existing cable and reconnect that cable between any two nodes.

Return the minimum number of cable moves needed to make every node connected. Return -1 when the network does not contain enough cables to connect all nodes.

Function

minimumEdgeMoves(n: int, edges: int[][]) → int

Examples

Example 1

n = 4edges = [[0,1],[0,2],[1,2]]return = 1

One cycle edge can be moved to attach the isolated node.

Example 2

n = 6edges = [[0,1],[0,2],[0,3],[1,2]]return = -1

Four cables cannot connect six nodes.

Constraints

  • 1 <= n <= 100000.
  • Every edge has two valid node IDs.
  • Self-loops and parallel edges are allowed and still count as available cables.

More Amazon problems

See Amazon hiring insights
public int minimumEdgeMoves(int n, int[][] edges) {
  // write your code here
}
n4
edges[[0,1],[0,2],[1,2]]
expected1
Checking account…