#2246
Longest Path With Different Adjacent Characters
HardArrayStringTreeDepth-First SearchGraph TheoryTopological SortDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses Depth-First Search (DFS) to traverse the tree while keeping track of the longest paths from each node. By only considering paths where adjacent characters differ, we efficiently compute the maximum path length.
⚙️
Algorithm
3 steps- 1Step 1: Build the tree from the parent array.
- 2Step 2: Perform a DFS starting from the root node, calculating the longest valid path for each node.
- 3Step 3: For each node, keep track of the two longest paths from its children that have different characters.
solution.py26 lines
1# Full working Python code
2from collections import defaultdict
3
4def longestPath(parent, s):
5 n = len(s)
6 graph = defaultdict(list)
7 for i in range(1, n):
8 graph[parent[i]].append(i)
9 max_length = 0
10
11 def dfs(node):
12 nonlocal max_length
13 longest1, longest2 = 0, 0
14 for child in graph[node]:
15 child_length = dfs(child)
16 if s[node] != s[child]:
17 if child_length > longest1:
18 longest2 = longest1
19 longest1 = child_length
20 elif child_length > longest2:
21 longest2 = child_length
22 max_length = max(max_length, longest1 + longest2 + 1)
23 return longest1 + 1
24
25 dfs(0)
26 return max_lengthℹ
Complexity note: This complexity is due to the single traversal of all nodes in the tree, which is efficient for the given constraints.
- 1The longest path can be derived from the longest two distinct character paths from any node.
- 2DFS is a powerful technique for tree traversal, allowing us to explore all paths efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.