2246. Longest Path With Different Adjacent Characters LeetCode Solution

In this guide, you will get 2246. Longest Path With Different Adjacent Characters LeetCode Solution with the best time and space complexity. The solution to Longest Path With Different Adjacent Characters problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Longest Path With Different Adjacent Characters solution in C++
  4. Longest Path With Different Adjacent Characters solution in Java
  5. Longest Path With Different Adjacent Characters solution in Python
  6. Additional Resources
2246. Longest Path With Different Adjacent Characters LeetCode Solution image

Problem Statement of Longest Path With Different Adjacent Characters

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.

Example 1:

Input: parent = [-1,0,0,1,1,2], s = “abacbe”
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
It can be proven that there is no longer path that satisfies the conditions.

Example 2:

Input: parent = [-1,0,0,0], s = “aabc”
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.

Constraints:

n == parent.length == s.length
1 <= n <= 105
0 <= parent[i] = 1
parent[0] == -1
parent represents a valid tree.
s consists of only lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

2246. Longest Path With Different Adjacent Characters LeetCode Solution in C++

class Solution {
 public:
  int longestPath(vector<int>& parent, string s) {
    const int n = parent.size();
    int ans = 1;
    vector<vector<int>> graph(n);

    for (int i = 1; i < n; ++i)
      graph[parent[i]].push_back(i);

    longestPathDownFrom(graph, 0, s, ans);
    return ans;
  }

 private:
  int longestPathDownFrom(const vector<vector<int>>& graph, int u,
                          const string& s, int& ans) {
    int max1 = 0;
    int max2 = 0;

    for (const int v : graph[u]) {
      const int res = longestPathDownFrom(graph, v, s, ans);
      if (s[u] == s[v])
        continue;
      if (res > max1) {
        max2 = max1;
        max1 = res;
      } else if (res > max2) {
        max2 = res;
      }
    }

    ans = max(ans, 1 + max1 + max2);
    return 1 + max1;
  }
};
/* code provided by PROGIEZ */

2246. Longest Path With Different Adjacent Characters LeetCode Solution in Java

class Solution {
  public int longestPath(int[] parent, String s) {
    final int n = parent.length;
    List<Integer>[] graph = new List[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int i = 1; i < n; ++i)
      graph[parent[i]].add(i);

    longestPathDownFrom(graph, 0, s);
    return ans;
  }

  private int ans = 0;

  private int longestPathDownFrom(List<Integer>[] graph, int u, final String s) {
    int max1 = 0;
    int max2 = 0;

    for (final int v : graph[u]) {
      final int res = longestPathDownFrom(graph, v, s);
      if (s.charAt(u) == s.charAt(v))
        continue;
      if (res > max1) {
        max2 = max1;
        max1 = res;
      } else if (res > max2) {
        max2 = res;
      }
    }

    ans = Math.max(ans, 1 + max1 + max2);
    return 1 + max1;
  }
}
// code provided by PROGIEZ

2246. Longest Path With Different Adjacent Characters LeetCode Solution in Python

class Solution:
  def longestPath(self, parent: list[int], s: str) -> int:
    n = len(parent)
    ans = 0
    graph = [[] for _ in range(n)]

    for i in range(1, n):
      graph[parent[i]].append(i)

    def longestPathDownFrom(u: int) -> int:
      nonlocal ans
      max1 = 0
      max2 = 0

      for v in graph[u]:
        res = longestPathDownFrom(v)
        if s[u] == s[v]:
          continue
        if res > max1:
          max2 = max1
          max1 = res
        elif res > max2:
          max2 = res

      ans = max(ans, 1 + max1 + max2)
      return 1 + max1

    longestPathDownFrom(0)
    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.