Program to return number of smaller elements at right of the given list in Python


Suppose we have a list of numbers called nums, we will create a new list where each element in the new list is the number of smaller elements to the right hand side of that element in the original input list.

So, if the input is like nums = [4, 5, 9, 7, 2], then the output will be [1, 1, 2, 1, 0], as there is 1 smaller element to the right of 4, there is 1 smaller element to the right of 5, there are 2 smaller elements to the right of 9, there is 1 smaller element to the right of 7, there are no smaller elements to the right of 2.

To solve this, we will follow these steps −

  • res := a new list, inc := a new list

  • while nums is not empty, do

    • num := delete last element from nums

    • insert left most index to insert num in inc at the end of res

    • sorted list after inserting num in inc

  • return a list res[from index 0 to end]

Let us see the following implementation to get better understanding−

Example

 Live Demo

import bisect
class Solution:
   def solve(self, nums):
      res, inc = [], []
      while nums:
         num = nums.pop()
         res.append(bisect.bisect_left(inc, num))
         bisect.insort(inc, num)
      return res[::-1]
ob = Solution()
nums = [4, 5, 9, 7, 2]
print(ob.solve(nums))

Input

[4, 5, 9, 7, 2]

Output

[1, 1, 2, 1, 0]

Updated on: 10-Oct-2020

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements