Ride-hailing app~15 min2s · 256 MBtarget O(n^2) time, O(n) spaceclassic twin: lc-547bfs
A ride-hailing app divides a country into n service zones. Two zones are linked when drivers regularly cross between them. Zone a may be linked to zone b directly, or only through a chain of other zones.
Your team lead says: "Each separate group of connected zones gets its own operations team. A group is a province. Tell me how many provinces there are."
You work on the zone planner. It receives the links as a table: row i shows which zones zone i is linked to.
Write count_provinces(links).
links is an n × n table of 0 and 1. links[i][j] = 1 means zones i and j are linked directly.links[i][j] = links[j][i], and links[i][i] = 1.Input: links = [[1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 1], [0, 0, 0, 1, 1]]
Output: 2Zones 0 and 2 are linked, zones 1 and 3 are linked, and zones 3 and 4 are linked. A search starts at the first zone that no earlier search reached and queues every zone linked to the zone it takes, one by one.
| Zone that starts a search | Zones taken from the queue, in order | Provinces so far |
|---|---|---|
| 0 | 0, 2 | 1 |
| 1 | 1, 3, 4 | 2 |
Zones 0 and 2 form one province. Zones 1, 3 and 4 form the other.
Input: links = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Output: 3No zone is linked to another, so each is its own province.
Input: links = [[1]]
Output: 1One zone is one province.
1 ≤ n ≤ 1,000, where n = len(links)links has n entries, each 0 or 1links[i][i] = 1 and links[i][j] = links[j][i]The table has up to a million entries, so reading it alone costs a million steps. A search that looks at one table row for each zone it takes costs n², which is a million steps. Working out whether every pair of zones is connected, with three nested loops, costs about a billion.