Count Smaller Numbers - Implementation

Here is the implementation using merge sort:

function countSmaller(nums):
    n = nums.length
    counts = array of n zeros
    indices = [0, 1, 2, ..., n-1]

    mergeSort(nums, indices, counts, 0, n - 1)
    return counts

function merge(nums, indices, counts, left, mid, right):
    temp = []
    i = left, j = mid + 1
    rightCount = 0

    while i <= mid and j <= right:
        if nums[indices[j]] < nums[indices[i]]:
            temp.append(indices[j])
            rightCount += 1
            j += 1
        else:
            counts[indices[i]] += rightCount
            temp.append(indices[i])
            i += 1

This runs in O(nlogn)O(n \log n) time and O(n)O(n) space.