From 0968d73de88e667cb779c3f6b435c1096449cdf9 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Mon, 20 Oct 2025 23:22:55 +0530 Subject: [PATCH] Add countBSTs method to calculate unique BSTs Implement a method to count unique BSTs for given elements. --- October_2025/potd_20_10_2025.java | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 October_2025/potd_20_10_2025.java diff --git a/October_2025/potd_20_10_2025.java b/October_2025/potd_20_10_2025.java new file mode 100644 index 0000000..a8822a6 --- /dev/null +++ b/October_2025/potd_20_10_2025.java @@ -0,0 +1,44 @@ +class Solution { + public ArrayList countBSTs(int[] arr) { + // Code here + + int[] cloned = arr.clone(); + ArrayList ans = new ArrayList<>(); + HashMap 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 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; + } +}