Number of Good Paths

Hard Topics Company Tags

An undirected tree has n nodes labeled from 0 to n - 1. The array vals gives each node's value, and each pair [u, v] in edges connects two nodes.

A path is good when its endpoints have equal values and no node along the path has a larger value than those endpoints. A path cannot visit a node more than once.

Return the number of distinct good paths. Every single node counts as a good path. Count a path and its reverse only once.

Diagram nodes show node index:value.

Example 1:

Number of Good Paths, example 1: illustration of the example

Input: vals = [2,1,2]
edges = [[0,1],[1,2]]

Output: 4

Explanation: The three single-node paths are good. The path 0 → 1 → 2 is also good: its endpoints both have value 2, and the middle node has value 1. These are the 4 distinct good paths.

Example 2:

Number of Good Paths, example 2: illustration of the example

Input: vals = [1,3,1]
edges = [[0,1],[1,2]]

Output: 3

Explanation: Each single node forms a good path. The path between nodes 0 and 2 is not good because its middle value, 3, exceeds their value of 1. Thus only the 3 single-node paths count.

Example 3:

Number of Good Paths, example 3: illustration of the example

Input: vals = [4,4,4]
edges = [[0,1],[0,2]]

Output: 6

Explanation: All values are equal, so every path is good. There are 3 single-node paths and 3 paths connecting pairs of distinct nodes, for a total of 6.

Constraints:

  • n == vals.length
  • 1 <= n <= 30000
  • 0 <= vals[i] <= 100000
  • edges.length == n - 1
  • Each edge contains two distinct integer node labels between 0 and n - 1.
  • The edges form a connected, undirected tree.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.