Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2246: Longest Path With Different Adjacent Characters

In this guide, we solve Leetcode #2246 Longest Path With Different Adjacent Characters in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Tree, Depth-First Search, Graph, Topological Sort, Array, String

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

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. It can be proven that there is no longer path that satisfies the conditions.

Python Solution

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 + 1

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n), where nnn is the number of nodes. The space complexity is O(n)O(n)O(n), where nnn is the number of nodes.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy