

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
- Related Questions & Answers
- Accessing all elements at given Python list of indexes
- Number of smaller and larger elements - JavaScript
- Python Program that print elements common at specified index of list elements
- Python Program to Extract Strings with at least given number of characters from other list
- Python program to right rotate the elements of an array
- Python program to remove elements at Indices in List
- Python - Ways to format elements of given list
- Python program to print elements which are multiples of elements given in a list
- Program to count number of elements are placed at correct position in Python
- Program to find minimum length of first split of an array with smaller elements than other list in Python
- Find sum of frequency of given elements in the list in Python
- Return the modified Bessel function evaluated at each of the elements of x in Python
- Sum of smaller elements of nodes in a linked list in C++
- Program to find the kth missing number from a list of elements in Python
- Python Program for Number of elements with odd factors in the given range