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 reordernums 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.
Number of Ways to Reorder Array to Get Same BST — Solution
The key insight is that for any BST, the root must appear first, then left and right subtree elements can be interleaved in C(left_size + right_size, left_size) ways. Best approach uses recursive combinatorics to count arrangements without generating them. Time: O(n²), Space: O(n)
Common Approaches
✓
Generate All Permutations
⏱️ Time: O(n! × n)
Space: O(n)
This approach generates all possible permutations of the input array, builds a BST from each permutation, and counts how many result in the same tree structure as the original.
Recursive with Memoization
⏱️ Time: O(n²)
Space: O(n)
Build the BST structure once, then recursively count valid arrangements by considering that the root must come first, followed by any interleaving of left and right subtree elements.
Generate All Permutations — Algorithm Steps
Generate all permutations of the array
Build BST from each permutation
Compare each BST with original BST
Count matching BSTs
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Original Array
Start with [2,1,3]
2
Generate Permutations
Create all 6 possible arrangements
3
Check Each
Build BST from each and compare with original
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MOD 1000000007
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
struct TreeNode* buildBST(int* arr, int n) {
if (n == 0) return NULL;
struct TreeNode* root = createNode(arr[0]);
for (int i = 1; i < n; i++) {
struct TreeNode* curr = root;
while (1) {
if (arr[i] < curr->val) {
if (curr->left) {
curr = curr->left;
} else {
curr->left = createNode(arr[i]);
break;
}
} else {
if (curr->right) {
curr = curr->right;
} else {
curr->right = createNode(arr[i]);
break;
}
}
}
}
return root;
}
int treesEqual(struct TreeNode* t1, struct TreeNode* t2) {
if (!t1 && !t2) return 1;
if (!t1 || !t2) return 0;
return t1->val == t2->val && treesEqual(t1->left, t2->left) && treesEqual(t1->right, t2->right);
}
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int permute(int* nums, int n, int start, struct TreeNode* originalBST) {
if (start == n) {
return treesEqual(buildBST(nums, n), originalBST) ? 1 : 0;
}
int count = 0;
for (int i = start; i < n; i++) {
swap(&nums[start], &nums[i]);
count += permute(nums, n, start + 1, originalBST);
swap(&nums[start], &nums[i]);
}
return count;
}
int solution(int* nums, int n) {
struct TreeNode* originalBST = buildBST(nums, n);
return permute(nums, n, 0, originalBST) % MOD;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
// Parse JSON array
int nums[50];
int n = 0;
char* token = strtok(line + 1, ",]");
while (token != NULL) {
nums[n++] = atoi(token);
token = strtok(NULL, ",]");
}
printf("%d\n", solution(nums, n));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n! × n)
Generate n! permutations, each taking O(n) time to build and compare BST
n
2n
⚠ Quadratic Growth
Space Complexity
O(n)
Space for storing permutation and BST nodes
n
2n
⚡ Linearithmic Space
28.0K Views
MediumFrequency
~35 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.