<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]:
        def helper(nums):
            if len(nums) == 0:
                return [], []
            if len(nums) == 1:
                return [0], [0]
            split = len(nums) // 2
            l_nums = nums[:split]
            r_nums = nums[split:]

            l_counts, l_permutation = helper(l_nums)
            r_counts, r_permutation = helper(r_nums)
            r_idx = 0
            for idx in range(split):
                curr_val = l_nums[l_permutation[idx]]
                while r_idx < len(r_permutation) and r_nums[r_permutation[r_idx]] < curr_val:
                    r_idx += 1
                l_counts[l_permutation[idx]] += r_idx

            
            l_counts.extend(r_counts)
            rval_permutation = []
            l_idx = 0
            r_idx = 0
            while l_idx < len(l_permutation) and r_idx < len(r_permutation):
                l_val = l_nums[l_permutation[l_idx]]
                r_val = r_nums[r_permutation[r_idx]]
                if l_val < r_val:
                    rval_permutation.append(l_permutation[l_idx])
                    l_idx += 1
                else:
                    rval_permutation.append(r_permutation[r_idx] + split)
                    r_idx += 1

            while l_idx < len(l_permutation):
                rval_permutation.append(l_permutation[l_idx])
                l_idx += 1
            while r_idx < len(r_permutation):
                rval_permutation.append(r_permutation[r_idx] + split)
                r_idx += 1
            return l_counts, rval_permutation
        return helper(nums)[0]


2240