<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Node:
    def __init__(self, l, r):
        self.l = l
        self.r = r
        self.left = None
        self.right = None
        self.cnt = 0


class SegmentTree:
    def __init__(self, min_num, max_num):
        self.root = Node(min_num, max_num)

    def update(self, idx, node=None):
        if node is None:
            node = self.root

        if node.l == idx and node.r == idx:
            node.cnt += 1
            return

        mid = (node.l + node.r) // 2

        if node.left is None:
            node.left = Node(node.l, mid)

        if node.right is None:
            node.right = Node(mid + 1, node.r)

        if idx <= mid:
            self.update(idx, node.left)
        else:
            self.update(idx, node.right)

        node.cnt = node.left.cnt + node.right.cnt

    def query(self, st, end, node=None):
        if node is None:
            node = self.root

        if node.l == st and node.r == end:
            return node.cnt

        mid = (node.l + node.r) // 2

        if node.left is None:
            node.left = Node(node.l, mid)

        if node.right is None:
            node.right = Node(mid + 1, node.r)

        if end <= mid:
            return self.query(st, end, node.left)
        elif st > mid:
            return self.query(st, end, node.right)

        left_sol = self.query(st, mid, node.left)
        right_sol = self.query(mid + 1, end, node.right)

        return left_sol + right_sol


class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:

        min_num, max_num = min(nums), max(nums)
        tree = SegmentTree(min_num - 1, max_num + 1)

        ans = [0] * len(nums)
        for idx in range(len(nums) - 1, -1, -1):
            vals = tree.query(min(min_num, nums[idx] - 1), nums[idx] - 1)
            ans[idx] = vals
            tree.update(nums[idx])

        return ans
4196