<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 Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:

        nums_cpy = [num for num in nums]
        nums_cpy.sort()
        ranks = {num: i for i, num in enumerate(sorted(set(nums)))}
        rank = len(ranks)
        arr = [0 for i in range(rank)]

        t = [0] * (4 * len(arr))
        n = len(arr)

        def build(v, tl, tr):
            if tl == tr:
                t[v] = arr[tl]
                return

            tm = (tl + tr) // 2

            build(2 * v + 1, tl, tm)
            build(2 * v + 2, tm + 1, tr)
            t[v] = t[2 * v + 1] + t[2 * v + 2]

        build(0, 0, len(arr) - 1)

        def update(rank):
            def _update(v, tl, tr: int):
                if tl == tr:
                    t[v] += 1
                    return
                tm = (tl + tr) // 2
                if rank <= tm:
                    _update(2 * v + 1, tl, tm)
                else:
                    _update(2 * v + 2, tm + 1, tr)

                t[v] = t[2 * v + 1] + t[2 * v + 2]

            _update(0, 0, len(arr) - 1)
            arr[rank] += 1
        def find(left, right):
            def _find(v, tl, tr, l, r):
                if l > r:
                    return 0

                if l == tl and r == tr:
                    return t[v]

                tm = (tl + tr) // 2

                return _find(2 * v + 1, tl, tm, l, min(tm, r)) + _find(2 * v + 2, tm + 1, tr, max(l, tm + 1), r)

            return _find(0, 0, n - 1, left, right)

        sols = []



        for num in reversed(nums):
            sols.append(find(0, ranks[num] - 1))
            update(ranks[num])

        return sols[::-1]
49555