<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]:

        self.n = len(nums)
        # Need this to keep original indices of the elements when doing
        # merge sort to update the ans accordingly
        nums_tuple = [(nums[i], i) for i in range(self.n)]
        self. ans = [0 for _ in range(self.n)]

        # We sort in descending order
        self.merge_sort(nums_tuple, 0, self.n - 1)
        return self.ans

    


    def merge(self, nums, low, mid, high):
        # print(nums[low: high + 1])
        l = low
        r = mid + 1
        temp = []
        while l <= mid and r <= high:
            if nums[l][0] > nums[r][0]:
                temp.append(nums[l])
                # right is smaller than left
                # print(f"Updating ans with idx: {nums[l][1]} : {(high - r + 1)}")
                self.ans[nums[l][1]] += (high - r + 1)
                l += 1
            else: 
                
                temp.append(nums[r])
                r += 1
        # add leftover elements to the array
        while l <= mid: 
            temp.append(nums[l])
            l += 1
        
        while r <= high: 
            temp.append(nums[r])
            r += 1
        
        # update original nums with sorted array
        for i in range(low , high + 1):
            nums[i] = temp[i - low]

    # basic merge sort recurrence. 
    def merge_sort(self, nums, low, high):

        if low >= high: 
            return 
        
        mid =  (high + low) // 2

        self.merge_sort(nums, low, mid)
        self.merge_sort(nums, mid + 1, high)
        self.merge(nums, low, mid, high)
1967