LeetCode Solution: Number of Good Paths

 Question: 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. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.

Constraints:

  • n == vals.length
  • 1 <= n <= 3 * 104
  • 0 <= vals[i] <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • edges represents a valid tree.

 

Solution: To solve this problem, you can use a depth-first search (DFS) algorithm to traverse the tree, starting from each node. For each node, you can check whether the path from that node to any of its descendant nodes satisfies the conditions for a good path. If it does, you can increment a counter variable.

This algorithm first convert the input edge list to adjacency list to traverse the tree easily. Then it iterates over all the nodes and for each node it calls a dfs function to traverse the tree and check the conditions for good path. If the path is good it increments the counter variable. Finally, it returns the count of good paths.


class Solution {

    int[] parents;

    private int find(int x){

        if(x != parents[x]) 

            parents[x] = find(parents[x]);

        return parents[x];

    }

    public int numberOfGoodPaths(int[] vals, int[][] edges) {

        int n = vals.length;

        if(n == 1) return 1;

        parents = new int[n];

        List<Integer> ids = new ArrayList<>();

        for(int i = 0; i < n; i++){

            parents[i] = i;

            ids.add(i);

        }


        Map<Integer, Set<Integer>> graph = new HashMap<>();

        

        for (int[] edge : edges) {

            int u = edge[0];

            int v = edge[1];

            

            graph.putIfAbsent(u, new HashSet<>());

            graph.putIfAbsent(v, new HashSet<>());

            

            graph.get(u).add(v);

            graph.get(v).add(u);

        }


        Collections.sort(ids, (a, b) -> (vals[a] - vals[b]));


        int ret = 0;

        for (int i = 0; i < n; i++) {

            int j = i + 1;

            while(j < n && vals[ids.get(j)] == vals[ids.get(i)]) j++;

            for (int k = i; k < j; k++) {

                int x = ids.get(k);

                for(int neighbor : graph.get(x)){

                    if (vals[x] >= vals[neighbor]) {

                        parents[find(x)] = find(neighbor);

                    }

                }

            }

            Map<Integer, Integer> temp = new HashMap<>();

            for(int k = i; k < j; k++){

                int root = find(ids.get(k));

                temp.put(root, temp.getOrDefault(root, 0) + 1);  // # of current val in the {root} group

            }


            for (int v : temp.values()){

                ret += v * (v + 1) / 2;

            }

            

            i = j - 1;

        }

        

        return ret;

    }

}

No comments:

Post a Comment