Longest Path in a Tree With No Equal Adjacent Labels

Last updated: November 29, 2026

Quick Overview

Given a rooted tree as a parent array and a string assigning a character label to each node, return the number of nodes on the longest path in which no two adjacent nodes share the same label.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a rooted tree as a parent array and a string assigning a character label to each node, return the number of nodes on the longest path in which no two adjacent nodes share the same label.

An onsite question combining tree diameter with a constraint, in the style Google uses to see whether you can adapt a known DFS pattern. The interviewer checks that you track the best downward chain per node and combine the top two at each node, all without recursion.

What the Interviewer Expects
  • Compute for each node the longest valid downward chain
  • At each node combine the two longest child chains with different labels
  • Skip children that share the node's label
  • Process nodes in post-order iteratively
  • Track the global best while computing chains
Key Topics to Cover
tree DP
diameter
post-order
DFS
top-two tracking
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if the constraint is that labels must strictly increase along the path?
  • Return the path itself.
  • What if edges have weights and you want the heaviest valid path?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: parent list (parent[0] = -1), string s of labels.
  • Path is any simple path in the tree (it can bend at a node).
  • Output: max node count.
  • n up to 10510^5....
High-Level Design

This is the diameter pattern. For each node u, let down[u] be the longest valid chain starting at u and going down. For each child c with s[c] != s[u], the candidate is down[c]. Keep the t...


Submit Your Answer
Markdown supported