Practice problem · easy
A city metro has n stations, numbered 0 to n - 1. A track joins two stations, and trains run on it in both directions. The list of tracks is [a, b] pairs.
Some stations have no track at all, for example because a line is closed for works. You work on the route planner, and it must warn riders about these isolated stations.
Write isolated_stations(n, tracks).
n is the number of stations.tracks[i] = [a, b] is a track between two different stations. A track can be listed more than once.Input: n = 6, tracks = [[0, 1], [1, 2], [4, 2]]
Output: [3, 5]| Station | Tracks that name it | Isolated? |
|---|---|---|
| 0 | [0, 1] |
no |
| 1 | [0, 1], [1, 2] |
no |
| 2 | [1, 2], [4, 2] |
no |
| 3 | none | yes |
| 4 | [4, 2] |
no |
| 5 | none | yes |
Stations 3 and 5 have no track.
Input: n = 3, tracks = []
Output: [0, 1, 2]There are no tracks, so every station is isolated.
Input: n = 2, tracks = [[0, 1]]
Output: []One track touches both stations, so no station is isolated.
1 ≤ n ≤ 10^50 ≤ length of tracks ≤ 2 · 10^50 ≤ a, b < n and a ≠ b for every trackThere can be 100,000 stations and 200,000 tracks. Scanning every track for each station would be about twenty billion steps, far too slow.
Each track names two stations. Reading the tracks once and marking the stations they name is enough.
isolated_stations · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.