Skip to main content
Back to problems
#2421
Hard Algorithms

Number of good paths

Array Hash Table Tree Union-Find Graph Theory Sorting
56.3% acceptance
Feb 25, 2026
2445
113
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 that a path and its reverse are counted as the same path. A single node is also considered as a valid path.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn number_of_good_paths(vals: Vec<i32>, edges: Vec<Vec<i32>>) -> i32 {
    let n = vals.len();
    let mut adj: Vec<Vec<usize>> = vec![vec![]; n];
    for e in &edges {
      adj[e[0] as usize].push(e[1] as usize);
      adj[e[1] as usize].push(e[0] as usize);
    }

    let mut parent: Vec<usize> = (0..n).collect();
    // cnt[root] = number of nodes in this component that have val == vals[root]
    let mut cnt: Vec<i32> = vec![1; n];

    fn find(p: &mut Vec<usize>, x: usize) -> usize {
      if p[x] != x {
        p[x] = find(p, p[x]);
      }
      p[x]
    }

    fn union(p: &mut Vec<usize>, cnt: &mut Vec<i32>, a: usize, b: usize, vals: &[i32]) -> i32 {
      let ra = find(p, a);
      let rb = find(p, b);
      if ra == rb {
        return 0;
      }
      let mut added = 0i32;
      // Only count pairs if both roots have the same value
      if vals[ra] == vals[rb] {
        added = cnt[ra] * cnt[rb];
        let ca = cnt[ra];
        let cb = cnt[rb];
        p[rb] = ra;
        cnt[ra] = ca + cb;
      } else if vals[ra] > vals[rb] {
        // ra has larger val, rb's val-count doesn't contribute
        p[rb] = ra;
        // cnt[ra] unchanged
      } else {
        // rb has larger val
        p[ra] = rb;
        // cnt[rb] unchanged
      }
      added
    }

    // Sort nodes by value
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by_key(|&i| vals[i]);

    let mut ans = n as i32; // all single-node paths

    for &u in &order {
      for &v in &adj[u] {
        if vals[v] <= vals[u] {
          ans += union(&mut parent, &mut cnt, u, v, &vals);
        }
      }
    }

    ans
  }
}