315. Count of Smaller Numbers After Self
Problem description:
You are given an integer array nums
and you have to return a new counts
array. The counts
array has the property where counts[i]
is the number of smaller elements to the right of nums[i]
.
Example 1:
1 | Input: nums = [5,2,6,1] |
Example 2:
1 | Input: nums = [-1] |
Example 3:
1 | Input: nums = [-1,-1] |
Constraints:
1 <= nums.length <= 105
104 <= nums[i] <= 104
Solution:
create a sorted list to help count the smaller number
traverse starting from right
use bisect_left to find position to insert in the sorted list, that would be number of smaller element after this item.
bisect_insort to insert the item in sorted order
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: