Ctrl K

Longest Hike Through the Woods

Medium
A forest has n clearings numbered 0 to n - 1 and n - 1 trails. Trail trails[i] = [a, b] connects clearings a and b and can be walked either way. Every clearing can reach every other one, and by exactly one route that doesn't repeat itself (in other words, the trails form a tree). The hikers want to pick two clearings with the longest route between them. Return the number of trails on that route.
Example 1
trails=[[0, 1], [1, 2], [1, 3], [3, 4], [4, 5]] → 4

The longest route is 0 → 1 → 3 → 4 → 5 (or 2 → 1 → 3 → 4 → 5): 4 trails.

Example 2
trails=[[2, 0], [2, 1], [2, 3]] → 2

Every trail meets at clearing 2, so any route between two other clearings passes through it and uses 2 trails.

Example 3
trails=[] → 0

There is a single clearing and nowhere to go, so the answer is 0.

Constraints
  • 1 ≤ n ≤ 10⁴, n = len(trails) + 1
  • 0 ≤ a, b < n, a ≠ b
  • The trails form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsModule Build Order MediumCourse Enrollment Queue MediumBest Roots for a Tree MediumRoutes That Always End MediumLinks That Form a Single Tree Medium
loading Python…
Input
trails=[[0, 1], [1, 2], [1, 3], [3, 4], [4, 5]]
Expected
4

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