
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Accessing all elements at given Python list of indexes
- Find Number of Array Elements Smaller than a Given Number in Java
- Python program to print elements which are multiples of elements given in a list
- Python Program to Extract Strings with at least given number of characters from other list
- Python program to remove elements at Indices in List
- Python Program that print elements common at specified index of list elements
- Python Program to replace list elements within a range with a given number
- Program to find minimum length of first split of an array with smaller elements than other list in Python
- Program to find the kth missing number from a list of elements in Python
- Python Program to Find Number of Occurrences of All Elements in a Linked List
- Python - Ways to format elements of given list
- Program to count number of elements in a list that contains odd number of digits in Python
- Python program to right rotate the elements of an array
- Program to count number of elements are placed at correct position in Python
- Given the “legs” of a right triangle, return its hypotenuse in Python
