Dashboard Temp Share Shortlinks Frames API

HTMLify

day36.py
Views: 13 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import math

class Solution:
    def countBSTs(self, arr):
        n = len(arr)
        
        def get_catalan(k):
            if k == 0 or k == 1:
                return 1
            return math.comb(2 * k, k) // (k + 1)
            
        res = []
        for root_val in arr:
            left_count = 0
            right_count = 0
            
            for x in arr:
                if x < root_val:
                    left_count += 1
                elif x > root_val:
                    right_count += 1
            
            num_bsts = get_catalan(left_count) * get_catalan(right_count)
            res.append(num_bsts)
            
        return res