Number of Provinces

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Number of Provinces

Approach

Every unvisited city starts a new DFS and one province. DFS marks all cities in that connected component.

Complexity Analysis

Time
O(n²)
Space
O(n)

Pattern

Connected Components in Matrix

Why It Works

A province is exactly one connected component in the undirected city graph, and each node is visited once from its component root.

Updated Mar 2026