|
| 1 | +/** |
| 2 | + * 1569. Number of Ways to Reorder Array to Get Same BST |
| 3 | + * https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array nums that represents a permutation of integers from 1 to n. We are going to |
| 7 | + * construct a binary search tree (BST) by inserting the elements of nums in order into an |
| 8 | + * initially empty BST. Find the number of different ways to reorder nums so that the constructed |
| 9 | + * BST is identical to that formed from the original array nums. |
| 10 | + * |
| 11 | + * For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a |
| 12 | + * right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST. |
| 13 | + * |
| 14 | + * Return the number of ways to reorder nums such that the BST formed is identical to the original |
| 15 | + * BST formed from nums. |
| 16 | + * |
| 17 | + * Since the answer may be very large, return it modulo 109 + 7. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} nums |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var numOfWays = function(nums) { |
| 25 | + const MOD = BigInt(10 ** 9 + 7); |
| 26 | + const factorialCache = Array(nums.length).fill(null); |
| 27 | + factorialCache[0] = 1n; |
| 28 | + |
| 29 | + function calculatePermutations(arr) { |
| 30 | + if (arr.length < 3) return 1n; |
| 31 | + |
| 32 | + const root = arr[0]; |
| 33 | + const leftSubtree = []; |
| 34 | + const rightSubtree = []; |
| 35 | + |
| 36 | + for (let i = 1; i < arr.length; i++) { |
| 37 | + if (arr[i] < root) { |
| 38 | + leftSubtree.push(arr[i]); |
| 39 | + } else { |
| 40 | + rightSubtree.push(arr[i]); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + const leftPermutations = calculatePermutations(leftSubtree); |
| 45 | + const rightPermutations = calculatePermutations(rightSubtree); |
| 46 | + const totalNodes = BigInt(arr.length - 1); |
| 47 | + const leftNodes = BigInt(leftSubtree.length); |
| 48 | + |
| 49 | + return (helper(totalNodes, leftNodes) * leftPermutations * rightPermutations) % MOD; |
| 50 | + } |
| 51 | + |
| 52 | + function helper(n, k) { |
| 53 | + factorialCache[n] = computeFactorial(n); |
| 54 | + factorialCache[n - k] = computeFactorial(n - k); |
| 55 | + factorialCache[k] = computeFactorial(k); |
| 56 | + return factorialCache[n] / (factorialCache[k] * factorialCache[n - k]); |
| 57 | + } |
| 58 | + |
| 59 | + function computeFactorial(n) { |
| 60 | + if (factorialCache[n]) return factorialCache[n]; |
| 61 | + return n * computeFactorial(n - 1n); |
| 62 | + } |
| 63 | + |
| 64 | + return Number((calculatePermutations(nums) - 1n) % MOD); |
| 65 | +}; |
0 commit comments