Last Updated: 6 Oct, 2025

Tree Level Width

Hard
Asked in company
Amazon

Problem statement

You are given a generic (n-ary) tree structure representing a hierarchy. The tree has N nodes, numbered from 0 to N-1. The structure is described by a parent array, where the i-th element denotes the parent of node i. The root of the tree is indicated by a parent value of -1.


Your task is to write a program that counts the number of nodes at each depth (or level) of the tree. The root is at depth 0, its children are at depth 1, and so on.


Input Format:
The first line contains an integer 'n', representing the size of both arrays.

The second line contains 'n' space-separated integers, representing the elements of array 'a'.

The third line contains 'n' space-separated integers, representing the elements of array 'b'.


Output Format:
Print a single integer, which is the maximum number of valid pairs that can be formed.


Note:
An element from array 'a' and an element from array 'b' can be part of only one pair. Once used, they cannot be used again to form another pair.