ORIGINAL CODING QUESTION
Mentoring tree diameter
Return the greatest edge distance between any two nodes of the tree. Direction from parents does not constrain the path.
Original exercise · medium. Editorial role relevance does not imply a company has asked this question.
Input and output
n, followed by n parent IDs. Node 0 is root with parent -1; every other parent is in [0, node ID).
Constraints
1 ≤ n ≤ 200; the parent list describes one connected rooted tree.
Example 1
Input
4 -1 0 0 1
Output
3
The path 3→1→0→2 has three edges.
Example 2
Input
1 -1
Output
0
No edges exist.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
The longest path need not pass through the root.
Hint 2
A farthest node from any start is a diameter endpoint.
Hint 3
Search again from that endpoint.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →