Not sure what to study next?

Get a personalised quant interview roadmap built around your upcoming interviews, strengths and weaknesses.

Takes a few minutes. Start with your target role and firms.

← Programming questions
Medium / PYTHON

Count Undirected Connected Components

graphs · depth_first_search 25 minute study target

Not completed

Challenge

Vertices are labelled 0 through n-1. Each [u, v] edge connects both directions. Return the number of connected components, counting isolated vertices as components too. Self-loops and duplicate edges do not join otherwise separate components.

Input and output contract

0 ≤ n ≤ 30,000; 0 ≤ edge count ≤ 60,000; all endpoints are valid vertex indices. If n=0, edges is empty and the answer is 0.

All tests follow this contract. You do not need to validate malformed input. Return the requested result from connected_components; printed output is not your answer. Standard-library tools are allowed. Implement your solution in Python 3.12.

Target complexity: O(n + e) time and auxiliary space

Return values are checked by type. Use the exact function name. Print output is not your answer. Tests have time and memory limits.

Public examples

Example 1

Arguments

[6, [[0, 1], [1, 2], [3, 4], [4, 3], [5, 5]]]

Expected return

3
Example 2

Arguments

[3, []]

Expected return

3
Example 3

Arguments

[0, []]

Expected return

0
Hint

Start a traversal from every vertex not yet visited. Count starts, not edges.

The worked solution unlocks after completion, or with Premium access.

connected_components.pyPython 3.12

Drafts are saved to your account, not to shared browser storage.

Sign in to submit code and save progress.

Results

Your results will appear here.

Hidden tests reveal only their pass/fail status, never their inputs or expected outputs. Runtime is observed wall time—not an inferred complexity class.

Join our Newsletter and Receive the Latest Updates!

Main Links

Trade Courses Assessments Interview Prep Contact Us

Social Media

Facebook Instagram YouTube

Legal

Terms and Conditions Privacy Policy Privacy settings

Talent Acquisition

Looking to hire exceptional quant talent?
See how we can help.

© 2026 EverythingQuant. All Rights Reserved.