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 Reordering Ways INPUT nums = [2, 1, 3] 2 1 3 idx 0 idx 1 idx 2 Resulting BST 2 1 3 Left Root Right ALGORITHM STEPS 1 Extract Root First element (2) is root 2 Split Array Left: [1], Right: [3] 1 3 L: R: 3 Count Interleavings C(left+right, left) C(2,1) = 2 4 Recurse Multiply subtree ways ways = C(2,1) * f(L) * f(R) [2,1,3] and [2,3,1] valid FINAL RESULT Valid Reorderings: [2, 1, 3] OK [2, 3, 1] OK Invalid Example: [3, 2, 1] X Creates different BST OUTPUT 2 2 ways to reorder Key Insight: The root must stay first. After that, left and right subtree elements can interleave in any order that preserves their relative order. Use combinations C(m+n, m) to count valid interleavings, then multiply by recursive results for each subtree. TutorialsPoint - Number of Ways to Reorder Array to Get Same BST | Optimal Solution
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