Longest Path With Different Adjacent Characters — LeetCode 2246 Python Solution
HardTreeDepth-First SearchGraphTopological SortArrayString
- Problem
- #2246
- Pattern
- Topological Sort
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
Python
class Solution:
def longestPath(self, parent: List[int], s: str) -> int:
def dfs(i: int) -> int:
mx = 0
nonlocal ans
for j in g[i]:
x = dfs(j) + 1
if s[i] != s[j]:
ans = max(ans, mx + x)
mx = max(mx, x)
return mx
g = defaultdict(list)
for i in range(1, len(parent)):
g[parent[i]].append(i)
ans = 0
dfs(0)
return ans + 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 2246. Longest Path With Different Adjacent Characters is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2246. Longest Path With Different Adjacent Characters?
- LeetCode 2246. Longest Path With Different Adjacent Characters is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2246. Longest Path With Different Adjacent Characters?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2246. Longest Path With Different Adjacent Characters?
- The Python solution on this page uses O(n), where n is the number of nodes auxiliary space.
- What topics does LeetCode 2246. Longest Path With Different Adjacent Characters cover?
- LeetCode 2246. Longest Path With Different Adjacent Characters is tagged Tree, Depth-First Search, Graph, Topological Sort, Array and String on LeetCode.