Skip to content
DeepForgeby svx
All problems
EasyGraph Algorithmsgraph-339

Edges Until Connected

Problem

Add undirected edges one at a time and report when the graph first becomes connected.

Return the number of edges processed at the moment all n nodes share a single component; count includes the edge that completed the connection. If the given edge list never connects the graph, return -1. A graph with n <= 1 is already connected and needs 0 edges.

Hint

Track the component count as unions succeed and stop the first time it equals 1.

Test cases

case 1
in: [4,[[0,1],[1,2],[2,3]]]
expected: 3
case 2
in: [4,[[0,1],[1,2],[2,3],[0,3]]]
expected: 3
case 3
in: [4,[[0,1],[2,3]]]
expected: -1
case 4
in: [1,[]]
expected: 0
case 5
in: [3,[[0,1],[0,2]]]
expected: 2
Starter codePython
def edges_until_connected(n, edges):
    # Your code here
    pass

5 test cases · run your code against them in the editor