Number of Good Paths - Problem

There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.

You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

A good path is a simple path that satisfies the following conditions:

  • The starting node and the ending node have the same value.
  • All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).

Return the number of distinct good paths.

Note: A path and its reverse are counted as the same path. For example, 0 → 1 is considered to be the same as 1 → 0. A single node is also considered as a valid path.

Input & Output

Example 1 — Basic Tree Structure
$ Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]
Output: 7
💡 Note: Good paths are: single nodes (5) + path 0→2→3 (nodes 0,3 both have value 1) + path 1→2→4 (nodes 1,4 both have value 3) = 5 + 1 + 1 = 7 total paths
Example 2 — All Same Values
$ Input: vals = [1,1,2,1,1], edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 10
💡 Note: Many good paths exist between nodes with value 1: all single nodes (5) + pairs of nodes with value 1 that can connect through node 2 (value 2) = 5 + 5 = 10 paths
Example 3 — Simple Path
$ Input: vals = [1], edges = []
Output: 1
💡 Note: Single node forms a valid good path by itself

Constraints

  • 1 ≤ n ≤ 3 * 104
  • 0 ≤ vals[i] ≤ 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • The given edges represent a valid tree

Visualization

Tap to expand
Good Paths in Tree: Same-Value Endpoints, Valid Intermediate Nodes1Node 03Node 12Node 21Node 33Node 4Good Paths Found:• 5 single-node paths• Node 0→2→3 (values 1,2,1) ✓• Node 1→2→4 (values 3,2,3) ✓Total: 7 Good Paths
Understanding the Visualization
1
Input Tree
Tree with node values: [1,3,2,1,3]
2
Find Good Paths
Paths where endpoints have same value, intermediate ≤ endpoint
3
Count Paths
Single nodes (5) + valid pairs (2) = 7 total
Key Takeaway
🎯 Key Insight: Process nodes by ascending values to ensure path validity constraints
Asked in
Google 15 Facebook 12 Amazon 8
18.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen