Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST.

Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.

For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.

Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.

Since the answer may be very large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3]
Output: 2
💡 Note: Root 2 must come first. Left subtree has [1], right has [3]. Valid arrangements: [2,1,3] and [2,3,1] both build the same BST structure.
Example 2 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one element, so only one possible arrangement that builds the BST.
Example 3 — Linear Tree
$ Input: nums = [3,1,2]
Output: 1
💡 Note: Forms a tree where 3 is root, 1 is left child, 2 is right child of 1. Only one valid arrangement maintains this structure.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ nums.length
  • All integers in nums are distinct

Visualization

Tap to expand
BST Arrangements: From Array [2,1,3]Input: [2,1,3]213BST StructureValid: [2,1,3] ✓Valid: [2,3,1] ✓Invalid: [1,2,3] ✗Different root = Different BSTAnswer: 2 valid arrangements
Understanding the Visualization
1
Input Array
Given array [2,1,3] to build BST
2
Build BST
Construct BST: 2 as root, 1 left, 3 right
3
Count Arrangements
Find all arrangements that build same BST: [2,1,3], [2,3,1]
Key Takeaway
🎯 Key Insight: Root must appear first, then left/right subtrees can be interleaved using combinatorics
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen