Count Connected Components in an Undirected Graph
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of graph connectivity and cycle detection, measuring competency in reasoning about connected components and the use of appropriate graph data structures.
Part 1: Count Connected Components in an Undirected Graph
Constraints
- 0 <= n <= 100000
- 0 <= len(edges) <= 200000
- Each edge is a pair `[u, v]` with `0 <= u, v < n` and `u != v`
- The graph is undirected
- Assume there are no duplicate edges
Examples
Input: (5, [[0, 1], [1, 2], [3, 4]])
Expected Output: 2
Explanation: Nodes 0, 1, and 2 form one component; nodes 3 and 4 form the other.
Input: (4, [])
Expected Output: 4
Explanation: There are no edges, so each node is its own connected component.
Input: (0, [])
Expected Output: 0
Explanation: An empty graph has zero connected components.
Input: (6, [[0, 1], [2, 3], [3, 4], [4, 2]])
Expected Output: 3
Explanation: Nodes 0 and 1 form one component, nodes 2, 3, and 4 form another, and node 5 is isolated.
Hints
- Think of each node as starting in its own group. Every time you connect two different groups, the total number of components decreases by 1.
- A Union-Find (Disjoint Set Union) structure can track component merges efficiently.
Part 2: Detect Whether an Added Edge Forms a Cycle in an Undirected Graph
Constraints
- 0 <= n <= 100000
- 0 <= len(edges) <= 200000
- Each edge is a pair `[u, v]` with `0 <= u, v < n` and `u != v`
- The graph is undirected
- Assume there are no duplicate edges
Examples
Input: (5, [[0, 1], [1, 2], [2, 0], [3, 4]])
Expected Output: True
Explanation: When edge [2, 0] is added, nodes 2 and 0 are already connected through 2-1-0, so a cycle is formed.
Input: (5, [[0, 1], [1, 2], [3, 4]])
Expected Output: False
Explanation: No edge connects two nodes that were already connected, so no cycle appears.
Input: (0, [])
Expected Output: False
Explanation: An empty graph has no edges, so no cycle can be formed.
Input: (4, [[0, 1], [1, 2], [2, 3], [0, 3]])
Expected Output: True
Explanation: Before adding [0, 3], nodes 0 and 3 are already connected through 0-1-2-3.
Hints
- In an undirected graph, an edge creates a cycle exactly when its two endpoints are already in the same connected component.
- Union-Find lets you check whether two nodes already share the same representative before merging them.