Number of Ways to Reorder Array to Get Same BST - Problem
Imagine you're given an array
For example, with
Goal: Count all possible reorderings that yield the same BST as the original array. Since this number can be astronomically large, return the result modulo 109 + 7.
nums representing a permutation of integers from 1 to n. Your task is to construct a Binary Search Tree (BST) by inserting elements from the array in order into an initially empty tree. The fascinating challenge is to determine how many different ways you can reorder this array while still producing the exact same BST structure.For example, with
[2,1,3]: we get root=2, left child=1, right child=3. The array [2,3,1] creates the identical BST, but [3,2,1] produces a completely different tree structure.Goal: Count all possible reorderings that yield the same BST as the original array. Since this number can be astronomically large, return the result modulo 109 + 7.
Input & Output
example_1.py โ Python
$
Input:
[2,1,3]
โบ
Output:
2
๐ก Note:
Arrays [2,1,3] and [2,3,1] both create BST with root=2, left child=1, right child=3. Other permutations like [1,2,3] create different BST structures.
example_2.py โ Python
$
Input:
[3,4,5,1,2]
โบ
Output:
5
๐ก Note:
Root=3 splits into left=[1,2] and right=[4,5]. Left subtree has 1 arrangement, right has 1 arrangement, and we can interleave them in C(4,2)=6 ways, but we must subtract 1 from final result: (1ร1ร6)-1=5.
example_3.py โ Python
$
Input:
[1,2,3]
โบ
Output:
1
๐ก Note:
This creates a completely right-skewed BST. Only one arrangement preserves this structure since each node has exactly one possible position.
Constraints
- 1 โค nums.length โค 1000
- nums is a permutation of integers from 1 to n
- All elements in nums are distinct
- Answer should be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Root Determines Structure
First element becomes root and partitions remaining elements
2
Recursive Partitioning
Elements < root go left, elements > root go right
3
Count Subtree Arrangements
Recursively count valid arrangements for each subtree
4
Combinatorial Interleaving
Use C(n,k) to count ways to merge left and right sequences
Key Takeaway
๐ฏ Key Insight: BST structure constraints allow us to use combinatorics instead of generating all permutations, reducing complexity from O(n!) to O(nยฒ)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code