Ctrl K

Distances to the Ring Road

Hard
A town has count junctions numbered 0 to count - 1 and exactly count two-way roads: roads[i] = [a, b] connects junctions a and b. Every junction can reach every other one, and the network contains exactly one closed loop, the ring road. The distance between two junctions is the smallest number of roads you need to drive along to get from one to the other. Return an array of length count whose i-th element is the distance from junction i to the nearest junction on the ring road. Junctions on the ring itself get 0.
Example 1
count=6, roads=[[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [1, 5]] → [0, 0, 0, 1, 2, 1]

The ring is junctions 0, 1, 2. Junction 3 is one step from 2, junction 4 is two steps away, and junction 5 is one step from 1.

Example 2
count=4, roads=[[3, 0], [0, 1], [1, 2], [2, 3]] → [0, 0, 0, 0]

All roads form a single ring, so every junction is already on it.

Example 3
count=5, roads=[[4, 3], [3, 2], [2, 1], [1, 3], [0, 4]] → [2, 0, 0, 0, 1]
Constraints
  • 3 ≤ count ≤ 10⁵
  • len(roads) = count
  • 0 ≤ a, b < count, a ≠ b
  • At most one road between any two junctions
  • The network is connected and has exactly one cycle
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Extra Link in a Rooted Tree HardPartners Side by Side HardWhich Machine to Cure HardWhich Machine to Unplug HardNews Through a Chain of Calls Hard
loading Python…
Input
count=6, roads=[[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [1, 5]]
Expected
[0, 0, 0, 1, 2, 1]

Run checks the first 3 tests in your browser. Submit checks all 37 tests on the server, hidden ones included.