Ctrl K

Distance Totals in a Road Tree

Hard
A district has count villages numbered 0 to count - 1. They are joined by count - 1 two-way roads: roads[i] = [a, b] is a road between villages a and b. Every village can reach every other one, and by exactly one route without repeats. The distance between two villages is the number of roads on the route between them. Return an array of length count whose i-th element is the sum of distances from village i to all the other villages.
Example 1
count=5, roads=[[0, 1], [1, 2], [1, 3], [3, 4]] → [8, 5, 8, 6, 9]

From village 1, villages 0, 2 and 3 are one road away and village 4 is two: 1 + 1 + 1 + 2 = 5. From village 4: 1 to village 3, 2 to village 1 and 3 each to villages 0 and 2, 9 in total.

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

There is only one village and nowhere to go.

Example 3
count=4, roads=[[2, 0], [2, 1], [2, 3]] → [5, 5, 3, 5]
Constraints
  • 1 ≤ count ≤ 3 · 10⁴
  • len(roads) = count - 1
  • 0 ≤ a, b < count, a ≠ b
  • The roads form a tree: all villages are connected
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDiscounted Trips Through a Tree HardSignal Through a Tree HardHeaviest Path in a Tree HardLongest Uphill Walk HardFewest Guards on a Tree Hard
loading Python…
Input
count=5, roads=[[0, 1], [1, 2], [1, 3], [3, 4]]
Expected
[8, 5, 8, 6, 9]

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