Ctrl K

Downward Path With One Repeat

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 the numbers on its nodes are distinct, with one allowed exception: a single value may appear exactly twice. 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], [2, 3, 5]], values=[5, 6, 5, 6] → [8, 3]

The full path 0 → 1 → 2 → 3 fails because both 5 and 6 repeat. The path 0 → 1 → 2 repeats only 5 and has length 7, while 1 → 2 → 3 repeats only 6 and has length 8. The answer is length 8 with 3 nodes.

Example 2
edges=[[0, 1, 2], [0, 2, 6]], values=[7, 7, 7] → [6, 2]

The value 7 may appear twice, so 0 → 2 qualifies: length 6 with 2 nodes.

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 Distinct Values 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], [2, 3, 5]], values=[5, 6, 5, 6]
Expected
[8, 3]

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