LeetCode 1319 Number of Operations to Make Network Connected - Example and Complexity Analysis

Walkthrough and analysis

Trace n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]].

55 cables, need 55 minimum for 66 computers. We have exactly enough.

Union operations: union(0,1), union(0,2), union(0,3), union(1,2) [already same], union(1,3) [already same].

After processing: {0,1,2,3} form one component. {4} alone. {5} alone.

Components: 33.

Operations needed: 31=23 - 1 = 2. Move 22 redundant cables to connect computers 4 and 5.

O(mα(n))O(m \cdot \alpha(n)) time for mm edges. O(n)O(n) space.