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:
Given nums = [5, 2, 6, 1]
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.
Return the array [2, 1, 1, 0].
Naive Implementation
The Idea: First I built an array the returns the index for the next smallest element in the array. Then iterating from the end, iterate to count the number of smallest elements beginning from the next smallest element.
Complexity: O(n + n^2) time and O(n) space
classSolution:defcountSmaller(self,nums):""" :type nums: List[int] :rtype: List[int] """defnext_smallest_element(nums): stack = [] next_smallest = [-1] *len(nums)for i, num inenumerate(nums, 0):while stack and stack[-1][1] > num: next_smallest[stack[-1][0]]= i stack.pop() stack.append((i, num))return next_smallestdefcount_num_smallested(start,ref): count =0for i inrange(start, len(nums)):if nums[i]< ref: count +=1return count next_smallest =next_smallest_element(nums) count_smaller = [0] *len(nums)for i inrange(len(nums) -2, -1, -1):if next_smallest[i]!=-1: count_smaller[i]=count_num_smallested(next_smallest[i], nums[i])return count_smaller