Skip to content
Closed
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
44 changes: 44 additions & 0 deletions October_2025/potd_20_10_2025.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public ArrayList<Integer> countBSTs(int[] arr) {
// Code here

int[] cloned = arr.clone();
ArrayList<Integer> ans = new ArrayList<>();
HashMap<Integer,Integer> h = new HashMap<>();


Arrays.sort(arr);
int n = arr.length;

// Step 1: find the catalan numbers
long[] catalan = new long[n+1];
catalan[0] = catalan[1] = 1;

for(int i = 2;i<=n;i++){
catalan[i] = 0;
for(int j = 0; j<i;j++){
catalan[i] += (catalan[j] * catalan[i-j-1]);
}
}

// Step 2: Find unique bsts for each distinct element

for(int i = 0;i < n; i++){
int L = i; // number elements in left subtree (elements are <= arr[i])
int R = n-i-1; // number of elements in right subtree (elements are > arr[i])

long bstsPossible = catalan[L] * catalan[R];
// bstsPossible = number of valid left subtrees * number of valid right subtrees

h.put(arr[i],(int) bstsPossible);
}

// Step 3: Form the answer list

for(int num: cloned){
ans.add(h.get(num));
}

return ans;
}
}