1

Given an array of integers, return a new array where each element in the new array is the number of smaller elements to the right of that element in the original input array. For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0].

import bisect

nums = list(input().split())
nums_to_the_right = []
result = []
sorted_nums = []

for num in reversed(nums):
    index = bisect.bisect_left(sorted_nums, num)
    result.append(index)
    bisect.insort(sorted_nums, num)

result.reverse()
print(result)

This code prints the correct result. The bisect_left function should return the index, which the current element must have to make the array sorted. The insort function puts the element in an array in such a way that the array remains sorted. I expect the whole piece of code to have O(n^2) complexity, but it's said to take O(nlogn) to work. Tell me, please, why?

1 Answers1

0

bisect module uses binary search algorithm to find insertion index. Complexity of each insertion with this algorithm - O(logn) (you can read very detailed description by following the link). You have n elements so the final complexity is O(nlogn). The final result.reverse() complexity is O(n) so it can be omitted in the summarized complexity calculation.

vurmux
  • 9,420
  • 3
  • 25
  • 45