Question bank › Graphs Dfs
Dsa Graphs Dfs Easy

Connected Components in a Graph

You are given a list of edges representing an undirected graph. Write a program that computes the number of connected components in the graph. Each edge is represented by two integers (u, v) indicating a connection between node u and node v. The nodes are labeled from 0 to n-1 where n is the number of nodes. Input format: - The first line contains two integers n (0 < n <= 1000) and m (0 <= m <= 10000), where n is the number of nodes and m is the number of edges. - The next m lines each contain two integers u and v (0 <= u, v < n) which denote an undirected edge. Output format: - Output a single integer representing the number of connected components. Example: Input: 5 3 0 1 1 2 3 4 Output: 2

Key concepts

graphdfsconnected components

Practise this out loud — free

Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.

🎙 Practise this question now
Part of InterviewLab's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.