Skip to content

ORIGINAL CODING QUESTION

Headcount at a reporting depth

A company hierarchy is given as a parent list, with the founder at node 0. Someone reporting directly to the founder is at depth 1, their reports are at depth 2, and so on. Return how many people sit at exactly depth k. If no one is that deep, return 0.

Open practice workspace

Original exercise · easy. Editorial role relevance does not imply a company has asked this question.

Input and output

n, followed by n parent IDs. Node 0 is the root with parent -1; every other parent is in [0, node ID). Then k.

Constraints

1 ≤ n ≤ 200; the parent list describes one connected rooted tree; 0 ≤ k ≤ 200.

Example 1

Input

5 -1 0 0 1 1 2

Output

2

Nodes 3 and 4 are both two levels below the founder.

Example 2

Input

3 -1 0 1 5

Output

0

The hierarchy is only two levels deep, so no one sits at depth 5.

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

Depth of a node is its parent depth plus one.

Hint 2

Parents appear before their children, so one forward pass fills every depth.

Hint 3

Count the depths equal to k.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →