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;

    }

}

LeetCode Solution: Longest Path With Different Adjacent Characters

 Question: You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.

You are also given a string s of length n, where s[i] is the character assigned to node i.

Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.

Constraints:

  • n == parent.length == s.length
  • 1 <= n <= 10^5
  • 0 <= parent[i] <= n - 1 for all i >= 1
  • parent[0] == -1
  • parent represents a valid tree.
  • s consists of only lowercase English letters.
Solution: You can solve this problem using dynamic programming.


  • Create an array dp of size n, where dp[i] represents the longest path ending at node i that satisfies the given condition.
  • Initialize dp[i] as 1 for all i, since every node itself is a valid path of length 1.
  • Iterate through the nodes in the tree in a bottom-up fashion, starting from the leaf nodes and working towards the root. For each node i, iterate through its children j and update dp[i] as follows:
                If s[i] is different from s[j], dp[i] = max(dp[i], dp[j] + 1)
  • Return the maximum value in the dp array.

Note that, in this solution, the time complexity is O(n) and the space complexity is O(n) as well.

class Solution {
    public int longestPath(int[] parent, String s) {
        int n = parent.length;
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < n; j++) {
                if (parent[j] == i && s.charAt(i) != s.charAt(j)) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }
        int max = 0;
        for (int i = 0; i < n; i++) {
            max = Math.max(max, dp[i]);
        }
        return max;
    }
}