Ctrl K

Camp Groups by Span

Hard
A nature reserve has camps campsites numbered from 1 to camps. They are joined by camps - 1 trails: trail [u, v] runs both ways between campsites u and v, and there is exactly one route between any two campsites. In other words, the campsites and trails form a tree. A **group** is a set of at least two campsites in which you can walk from any member to any other without stepping onto a campsite outside the set. Two groups are different if some campsite belongs to only one of them. The **span** of a group is the largest distance between two of its campsites, where distance is the number of trails on the route between them. Return an array of length camps - 1 whose element at index d - 1 is the number of groups with span exactly d.
Example 1
camps=5, trails=[[1, 2], [2, 3], [3, 4], [3, 5]] → [4, 5, 3, 0]

The four groups of two neighbouring camps have span 1. Span 2 belongs to {1,2,3}, {2,3,4}, {2,3,5}, {3,4,5} and {2,3,4,5}. Span 3 belongs to {1,2,3,4}, {1,2,3,5} and {1,2,3,4,5}.

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

Every trail meets at camp 4, so any group of two or more camps must include it: three pairs (span 1) and four groups where camp 4 is joined by two or three others (span 2). No group has span 3.

Example 3
camps=2, trails=[[2, 1]] → [1]
Constraints
  • 2 ≤ camps ≤ 15
  • len(trails) == camps - 1
  • trails[i] = [u, v], 1 ≤ u, v ≤ camps, u ≠ v
  • No trail repeats, and the trails connect all campsites into a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPalindrome-Ready Tree Paths HardSettle Up in the Fewest Transfers HardTwo Groups With the Same Average HardShortest Walk Through Every Node HardAssembling Fragments Hard
loading Python…
Input
camps=5, trails=[[1, 2], [2, 3], [3, 4], [3, 5]]
Expected
[4, 5, 3, 0]

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