1667. Signal Towers Within K

A hill region has n villages numbered 0..n-1, joined by n - 1 trails listed in edges so that every village can reach every other (the trails form a tree). A radio tower may be built in any village, and a tower serves every village that is at most k trails away from it, itself included.

Return the smallest number of towers that leaves every village served. Because each tower only reaches nearby villages, a single bottom-up pass over the tree can decide greedily where a tower is forced: remember, for each branch, how far its farthest unserved village is and how close its nearest tower is.

The trail list is not sorted. Aim for O(n) time and O(n) extra space, and avoid deep recursion because the tree can be a long chain.

Example 1

Input:
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]], k = 1
Output:
2
Explanation:

On a path of 5 nodes with k = 1, towers on nodes 1 and 3 together serve nodes 0 to 4, and one tower can serve at most 3 nodes.

Example 2

Input:
n = 7edges = [[0,1],[0,2],[0,3],[1,4],[2,5],[3,6]]k = 2
Output:
1
Explanation:

The centre node 0 reaches every node within 2 edges, so one tower is enough.

Example 3

Input:
n = 6, edges = [[0,1],[1,2],[2,3],[3,4],[4,5]], k = 1
Output:
2
Explanation:

On a path of 6 nodes each tower covers at most 3 nodes, and two towers on nodes 1 and 4 cover everything.

Constraints

1 ≤ n ≤ 105
1 ≤ k ≤ 20
edges has n - 1 pairs [u, v] describing a tree on nodes 0..n-1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…