Number of Connected Components
Detailed guide and Python implementation for the 'Number of Connected Components' problem.
1. Concept Overview
The 'Number of Connected Components' problem is a key challenge in the Graphs section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Number of Connected Components.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Number of Connected Components carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an undirected edge between ai and bi in the graph.
Return the number of connected components in the graph.
Write a function countComponents(n: int, edges: List[List[int]]) -> int.
- •1 <= n <= 2000
- •0 <= len(edges) <= 5000
- •edges[i].length == 2
- •0 <= ai, bi < n
Examples
n = 5, edges = [[0,1],[1,2],[3,4]]
2
Nodes 0, 1, 2 form one component, and nodes 3, 4 form another component.
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
1
All nodes are connected in a single path.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def count_components_opt(n, edges):
par = [i for i in range(n)]
rank = [1] * n
def find(n1):
res = n1
while res != par[res]:
par[res] = par[par[res]]
res = par[res]
return res
def union(n1, n2):
p1, p2 = find(n1), find(n2)
if p1 == p2: return 0
if rank[p2] > rank[p1]:
par[p1] = p2
rank[p2] += rank[p1]
else:
par[p2] = p1
rank[p1] += rank[p2]
return 1
res = n
for n1, n2 in edges: res -= union(n1, n2)
return resBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def count_components_brute(n, edges):
adj = {i: [] for i in range(n)}
for n1, n2 in edges:
adj[n1].append(n2)
adj[n2].append(n1)
visit = set()
def dfs(i):
if i in visit: return
visit.add(i)
for j in adj[i]: dfs(j)
res = 0
for i in range(n):
if i not in visit:
dfs(i)
res += 1
return resAlgorithm Pattern Checklist
When dealing with Graphs data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Find the Length of a List in Python
Learn how to find the length of a list in Python using the len() function. Understand the O(1) time complexity and checking counts.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.