|
| 1 | +/** |
| 2 | + * 2003. Smallest Missing Genetic Value in Each Subtree |
| 3 | + * https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a |
| 7 | + * 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is |
| 8 | + * the root, parents[0] == -1. |
| 9 | + * |
| 10 | + * There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. |
| 11 | + * You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for |
| 12 | + * node i. |
| 13 | + * |
| 14 | + * Return an array ans of length n where ans[i] is the smallest genetic value that is missing |
| 15 | + * from the subtree rooted at node i. |
| 16 | + * |
| 17 | + * The subtree rooted at a node x contains node x and all of its descendant nodes. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} parents |
| 22 | + * @param {number[]} nums |
| 23 | + * @return {number[]} |
| 24 | + */ |
| 25 | +var smallestMissingValueSubtree = function(parents, nums) { |
| 26 | + const n = parents.length; |
| 27 | + const result = new Array(n).fill(1); |
| 28 | + const children = Array.from({ length: n }, () => []); |
| 29 | + const seen = new Set(); |
| 30 | + let maxMissing = 1; |
| 31 | + |
| 32 | + for (let i = 1; i < n; i++) { |
| 33 | + children[parents[i]].push(i); |
| 34 | + } |
| 35 | + |
| 36 | + const nodeWithOne = nums.indexOf(1); |
| 37 | + if (nodeWithOne === -1) return result; |
| 38 | + |
| 39 | + let current = nodeWithOne; |
| 40 | + while (current !== -1) { |
| 41 | + const stack = [current]; |
| 42 | + while (stack.length) { |
| 43 | + const node = stack.pop(); |
| 44 | + seen.add(nums[node]); |
| 45 | + for (const child of children[node]) { |
| 46 | + if (!seen.has(nums[child])) stack.push(child); |
| 47 | + } |
| 48 | + } |
| 49 | + while (seen.has(maxMissing)) maxMissing++; |
| 50 | + result[current] = maxMissing; |
| 51 | + current = parents[current]; |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | +}; |
0 commit comments