Comment thread depth

Write codeEasy15 min

Your task

A discussion board keeps every comment on an article in one chronological list. Entry i of parent_of holds the position of the comment that comment i replies to, or -1 when comment i starts a new thread at the top level. An article can carry several top level comments, and moderators reinstate hidden replies, so a comment is not guaranteed to appear after the one it answers: a parent can sit at a later position than its child. The renderer needs an indent level for every comment. Return a list of the same length in which entry i is the depth of comment i, counting 0 for a top level comment, 1 for a direct reply, 2 for a reply to a reply, and so on. Keep the results in input index order. The input always describes a valid structure with no cycles.

Examples

comment_reply_depths(parent_of: list[int]) -> list[int]
Example 1
Inputcomment_reply_depths([-1, 0, 0, 1])
Output[0, 1, 1, 2]
Example 2
Inputcomment_reply_depths([-1, -1, 1])
Output[0, 0, 1]
Example 3
Inputcomment_reply_depths([2, -1, 1])
Output[2, 0, 1]