Tree Diameter
Real-world version: The Longest Walk in a Pipe NetworkThe statement here is our own: the same inputs, outputs and technique.
A network of junctions is joined by the pipes pipes, where pipes[i] = [a, b] is a two-way pipe between junction a and junction b. The network holds one more junction than it has pipes, and the junctions are numbered from 0 upwards. Every junction is reachable from every other, and there is no loop anywhere.
Return the greatest number of pipes on any walk between two junctions that never uses a pipe twice.
Examples
Example 1
- Input
- pipes = [[0, 1], [1, 2], [2, 3], [3, 4], [2, 5]]
- Output
- 4
Six junctions. The walk from 0 through 1, 2 and 3 to 4 uses four pipes, and so does the walk from 0 to 5 by way of 1 and 2 plus one more. Nothing longer exists, since junction 2 is where the two ends part company.
Example 2
- Input
- pipes = []
- Output
- 0
No pipes means a single junction, and a walk that goes nowhere uses none.
Example 3
- Input
- pipes = [[0, 1], [0, 2], [0, 3], [0, 4]]
- Output
- 2
Every junction hangs straight off junction 0, so the longest walk goes from one of them through 0 to another, using two pipes.
Constraints
- 0 <= pipes.length <= 9999
- pipes[i].length == 2
- 0 <= pipes[i][j] <= pipes.length
- The two ends of a pipe are different junctions.
- The pipes reach every junction and hold no loop.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def tree_diameter(pipes: list[list[int]]) -> int:public int treeDiameter(int[][] pipes)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Course Schedule IIReal-world version: Module Build OrderMedium
- Course ScheduleReal-world version: Apprenticeship Skill PlanMedium
- Find Eventual Safe StatesReal-world version: States From Which the Batch Always HaltsMedium
- Minimum Height TreesReal-world version: Courier Base on the Campus WalkwaysMedium