Ctrl K

Downward Path With Distinct Values

Hard
You are given a tree of n nodes numbered 0 to n − 1, rooted at node 0. The list edges describes it: [u, v, w] is an edge of length w between u and v. Node i holds the number values[i]. Consider paths that only go down: from some node to one of its descendants (a single node is a path too). A path qualifies if all the numbers on its nodes are distinct. The length of a path is the sum of its edge lengths. Return an array of two numbers: the greatest length of a qualifying path, and the smallest number of nodes among qualifying paths of that greatest length.
Example 1
edges=[[0, 1, 4], [1, 2, 3], [0, 3, 7]], values=[5, 6, 5, 8] → [7, 2]

The path 0 → 1 → 2 does not qualify: nodes 0 and 2 both hold 5. That leaves 0 → 1 (length 4), 1 → 2 (length 3) and 0 → 3 (length 7, 2 nodes), which is the best.

Example 2
edges=[[0, 1, 2], [1, 2, 2], [0, 3, 4]], values=[1, 2, 3, 4] → [4, 2]

Length 4 is reached by both 0 → 1 → 2 (3 nodes) and 0 → 3 (2 nodes). The length is 4 and the smaller node count is 2.

Example 3
edges=[[1, 0, 9]], values=[3, 3] → [0, 1]

Both nodes hold 3, so a path is a single node: length 0 with 1 node.

Constraints
  • 2 ≤ n ≤ 5·10⁴
  • len(edges) = n − 1, each edge is [u, v, w]
  • 0 ≤ u, v < n
  • 1 ≤ w ≤ 1000
  • len(values) = n
  • 0 ≤ values[i] ≤ 5·10⁴
  • The edges form a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDownward Path With One Repeat HardRoots That Fit the Guesses HardPalindromic Subtrees HardStop a Process Branch MediumPath Totals in a Coded Tree Medium
loading Python…
Input
edges=[[0, 1, 4], [1, 2, 3], [0, 3, 7]], values=[5, 6, 5, 8]
Expected
[7, 2]

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