1658. Pairs K Apart

A company org chart is stored as a tree of n staff numbered 0 to n-1; edges holds the n-1 reporting links as pairs [u, v] (direction is irrelevant). The distance between two staff members is the number of links on the unique route joining them.

Given the integer k, count the unordered pairs of different staff members whose distance is exactly k. The pair (a, b) and the pair (b, a) are the same pair and count once. Return the total as a long (n is at most 30000). Aim for O(n * k) time: starting a fresh search from every member costs O(n^2) and is too slow. Keep, for each member, how many people in its subtree lie 0, 1, ..., k links below it, and combine these counts child by child.

Example 1

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

The pairs at distance exactly 2 are (1,2), (1,3), (2,3) and (0,4), giving 4.

Example 2

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

Only the two ends of the path are 3 edges apart, so the answer is 1.

Constraints

1 ≤ n ≤ 3 * 104

1 ≤ k ≤ 50

edges.length == n - 1 and the edges form 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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n * k)
Space
O(n * k)

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…