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

"""
0 没有 lsb 所以 不用 bit[0]
i & -i 为 the rightmost set bit

 7 = 00111
-7 = 11001

Two's complement（二进制补码）：反码 + 1

00111 & 11001 = 00001 即 the rightmost set bit
00111 - 00001 = 00110 即 flip the rightmost set bit
"""

# Returns the least significant bit
lsb = lambda i: i & -i

# Adds value to existing value at index i.
def update(bit, i, value):
    i += 1
    while i < len(bit): # propagate the change to the end of the array
        bit[i] += value
        i += lsb(i) # add the least significant set bit

# Prefix sum from beginning to index i.
def query(bit, i):
    i += 1
    sum = 0
    while i > 0:
        sum += bit[i]
        i -= lsb(i) # flip the last set bit
    return sum

# Prefix sum in range [l, r]
def queryRange(bit, l, r):
    return query(bit, r) - query(bit, l - 1) if l > 0 else query(r)

def build_n(nums): # O(n)
    n = len(nums)
    bit = [None] + nums # 1-based
    for i in range(n):
        p = i + lsb(i) # parent
        if p <= n: bit[p] += bit[i]
    return bit

def build_nlogn(nums): # O(nlogn)
    bit = [None] + [0] * len(nums)
    for i, num in enumerate(nums):
        update(bit, i, num)
    return bit

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        MIN = int(1e4) + 1 # -1e4 <= nums[i]
        # bit = [0 for _ in range(MIN + max(nums) + 1)]
        bit = [0] * (MIN + max(nums) + 1)
        res = []
        for num in nums[::-1]: # nums.reverse()
            res.append(query(bit, MIN + num - 1)) # 右边 < 它的 数的个数
            update(bit, MIN + num, 1)
        return res[::-1]
38815