Comment on page

315 Count of Smaller Numbers After Self

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
class Solution:
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def next_smallest_element(nums):
stack = []
next_smallest = [-1] * len(nums)
for i, num in enumerate(nums, 0):
while stack and stack[-1][1] > num:
next_smallest[stack[-1][0]] = i
stack.pop()
stack.append((i, num))
return next_smallest
def count_num_smallested(start, ref):
count = 0
for i in range(start, len(nums)):
if nums[i] < ref:
count += 1
return count
next_smallest = next_smallest_element(nums)
count_smaller = [0] * len(nums)
for i in range(len(nums) - 2, -1, -1):
if next_smallest[i] != -1:
count_smaller[i] = count_num_smallested(next_smallest[i], nums[i])
return count_smaller