Related Articles

# Find MEX of every subtree in given Tree

• Difficulty Level : Hard
• Last Updated : 08 Sep, 2021

Given a Generic Tree consisting of N nodes numbered from 0 to N – 1 which is rooted at node 0 and an array val[] such that the value at each node is represented by val[i],  the task for each node is to find the value of MEX of its subtree.

The MEX value of node V is defined as the smallest missing positive number in a tree rooted at node V.

Examples:

Input: N = 6, edges = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {3, 5}}, val[] = {4, 3, 5, 1, 0, 2}
Output: [6, 0, 0, 3, 1, 0]
Explanation:
0(4)
/    \
1(3)    3(1)
/         /    \
2(5)     4(0)   5(2)

In the subtrees of:
Node 0: All the values in range [0, 5] are present, hence the smallest non-negative value not present is 6.
Node 1: The smallest non-negative value not present in subtree of node 1 is 0.
Node 2: The smallest non-negative value not present in subtree of node 2 absent is 0.
Node 3: All the values in range [0, 2] are present, hence the smallest non-negative value not present in subtree of node 3 is 3.
Node 4: The smallest non-negative value not present in subtree of node 4 is 1.
Node 5: The smallest non-negative value not present in subtree of node 5 is 0.

Approach: The given problem can be solved using DFS Traversal on the given Tree and performing the Binary Search to find the missing minimum positive integers in each node subtree. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## C++14

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Stores the edges of the tree``vector > edges;` `// Function to add edges``void` `add_edge(``int` `x, ``int` `y)``{``    ``edges.push_back({ x, y });``}` `// Function to merge two sorted vectors``vector<``int``> merge(vector<``int``>& a,``                  ``vector<``int``>& b)``{``    ``// To store the result``    ``vector<``int``> res;` `    ``int` `i = 0, j = 0;``    ``int` `n = a.size(), m = b.size();` `    ``// Iterating both vectors``    ``while` `(i < n && j < m) {``        ``if` `(a[i] < b[j])``            ``res.push_back(a[i++]);``        ``else` `if` `(b[j] < a[i])``            ``res.push_back(b[j++]);``    ``}` `    ``// Pushing remaining elements of``    ``// vector a``    ``while` `(i < n)``        ``res.push_back(a[i++]);` `    ``// Pushing remaining elements of``    ``// vector b``    ``while` `(j < m)``        ``res.push_back(b[j++]);` `    ``return` `res;``}` `// Function to perform the DFS Traversal``// that returns the subtree of node``// in sorted manner``vector<``int``> help(vector<``int``> tree[], ``int` `x,``                 ``int` `p, vector<``int``>& c,``                 ``vector<``int``>& sol)``{``    ``vector<``int``> res;``    ``res.push_back(c[x]);` `    ``// Iterate the childrens``    ``for` `(``auto` `i : tree[x]) {` `        ``// All values of subtree``        ``// i in sorted manner``        ``if` `(i != p) {``            ``vector<``int``> tmp``                ``= help(tree, i, x, c, sol);``            ``res = merge(res, tmp);``        ``}``    ``}` `    ``int` `l = 0, r = res.size() - 1;``    ``int` `ans = res.size();` `    ``// Binary search to find MEX``    ``while` `(l <= r) {``        ``// Find the mid``        ``int` `mid = (l + r) / 2;` `        ``// Update the ranges``        ``if` `(res[mid] > mid)``            ``r = mid - 1;``        ``else` `{``            ``ans = mid + 1;``            ``l = mid + 1;``        ``}``    ``}``    ``if` `(res != 0)``        ``ans = 0;` `    ``// Update the MEX for the current``    ``// tree node``    ``sol[x] = ans;` `    ``return` `res;``}` `// Function to find MEX of each``// subtree of tree``void` `solve(``int` `A, vector<``int``> C)``{``    ``int` `n = A;``    ``vector<``int``> tree[n + 1];``    ``for` `(``auto` `i : edges) {``        ``tree[i].push_back(i);``        ``tree[i].push_back(i);``    ``}``    ``vector<``int``> sol(n, 0);` `    ``// Function Call``    ``help(tree, 0, -1, C, sol);` `    ``// Printe the ans for each nodes``    ``for` `(``auto` `i : sol)``        ``cout << i << ``" "``;``}` `// Driver Code``int` `main()``{``    ``int` `N = 6;``    ``add_edge(0, 1);``    ``add_edge(1, 2);``    ``add_edge(0, 3);``    ``add_edge(3, 4);``    ``add_edge(3, 5);` `    ``vector<``int``> val = { 4, 3, 5, 1, 0, 2 };``    ``solve(N, val);` `    ``return` `0;``}`

## Javascript

 ``
Output:
`6 0 0 3 1 0`

Time Complexity: O(N*(N + log N))
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up