Ctrl K

Signal Through a Tree

Hard
A network of n nodes numbered 0 to n − 1 is shaped like a tree: edges[i] = [u, v] means nodes u and v are linked directly. The number of nodes is len(edges) + 1. At time 0 a single node is switched on, and the signal spreads through the network. Its speed depends on the number of the node it is entering: - an **odd** node lights up at time x if at least one of its neighbours was already lit at time x − 1; - an **even** node lights up at time x if at least one of its neighbours was already lit at time x − 2. For every node i, find the time at which the whole network is lit if node i is switched on first. The runs are independent: each one starts with the whole network off. Return the array of these times.
Example 1
edges=[[0, 1], [1, 2]] → [3, 2, 3]

From node 0: node 1 lights up at time 1 and node 2 at 1 + 2 = 3. From node 1: both even neighbours light up at time 2. From node 2 the picture mirrors node 0.

Example 2
edges=[[1, 0]] → [1, 2]

The signal needs 1 unit to reach odd node 1 from 0, but 2 units to reach even node 0 from 1.

Example 3
edges=[[0, 1], [0, 2], [0, 3]] → [2, 4, 3, 4]

A star centred at 0. Starting from leaf 1: the centre lights up at time 2, node 3 at 3 and node 2 at 4, so the answer is 4.

Constraints
  • 2 ≤ n ≤ 10⁵
  • len(edges) = n − 1
  • 0 ≤ u, v ≤ n − 1
  • edges form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDistance Totals in a Road Tree HardDiscounted Trips Through a Tree HardHeaviest Path in a Tree HardLongest Uphill Walk HardFewest Guards on a Tree Hard
loading Python…
Input
edges=[[0, 1], [1, 2]]
Expected
[3, 2, 3]

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