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;
    }
}

No comments:

Post a Comment