Tree Level Width

Hard
0/120
0 upvote
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.


Detailed explanation ( Input/output format, Notes, Images )
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.
Sample Input 1:
3
10 20 30
5 15 25


Sample Output 1:
3


Explanation for Sample 1:
We can form the following three pairs:
1. (10, 5) since 10 > 5
2. (20, 15) since 20 > 15
3. (30, 25) since 30 > 25
All elements are used, and we have a total of 3 pairs, which is the maximum possible.


Sample Input 2:
4
1 2 8 9
3 4 5 6


Sample Output 2:
2


Explanation for Sample 2:
The optimal way to form pairs is:
1. (8, 3) since 8 > 3
2. (9, 4) since 9 > 4
The elements 1 and 2 from array 'a' cannot be paired with any remaining elements from array 'b' (5 and 6). The maximum number of pairs is 2.


Expected Time Complexity:
The expected time complexity is O(n log n).


Constraints:
1 <= n <= 10^5
-10^9 <= a[i], b[i] <= 10^9

Time limit: 1 sec
Approaches (1)
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Tree Level Width
Full screen
Console