Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Input: nums = [-1]
Output: [0]
Input: nums = [-1,-1]
Output: [0,0]
The simplest approach is to check each element and count how many numbers after it are smaller. This involves iterating over each element and then iterating over subsequent elements to count the smaller numbers.
By using a BST, where each node contains the number of times it and all its left descendants have been inserted, we can efficiently insert each number in reverse order and count how many smaller elements have already been inserted.
Fenwick Tree is useful for maintaining prefix sums efficiently. We can translate the problem into finding the frequency of numbers, querying this frequency with a Fenwick Tree while iterating the array backwards.
This is a modification of merge sort. What we can do is keep track of how many elements are moved after an item in the merge process.