LeetCode 1971 Find if Path Exists - Example and Complexity Analysis

Walkthrough and analysis

Trace n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]].

Initially: each node is its own parent.

Union(0,1): parent[1] = 0. Components: {0,1}, {2}, {3}, {4}, {5}.

Union(0,2): parent[2] = 0. Components: {0,1,2}, {3}, {4}, {5}.

Union(3,5): parent[5] = 3. Components: {0,1,2}, {3,5}, {4}.

Union(5,4): find(5)=3, parent[4] = 3. Components: {0,1,2}, {3,4,5}.

Union(4,3): find(4)=3, find(3)=3. Already same. No change.

Check: find(0) = 0, find(5) = 3. Different. Return false.

O(Eα(n))O(E \cdot \alpha(n)) time where α\alpha is inverse Ackermann (nearly constant). O(n)O(n) space.