Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions 20 October Number of BST From Array
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public:
vector<int> countBSTs(vector<int>& arr) {
int n = arr.size();
vector<int> ans;
vector<int> vec = arr;
sort(vec.begin(), vec.end());

// Precompute Catalan numbers up to n
vector<long long> cat(n + 1, 0);
cat[0] = cat[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 0; j < i; j++) {
cat[i] += cat[j] * cat[i - j - 1];
}
}

for (int i = 0; i < n; i++) {
int idx = lower_bound(vec.begin(), vec.end(), arr[i]) - vec.begin();
int left = idx; // elements smaller than arr[i]
int right = n - idx - 1; // elements greater than arr[i]

long long total = cat[left] * cat[right];
ans.push_back((int)total);
}
return ans;
}
};