- Related Questions & Answers
- Accessing all elements at given Python list of indexes
- Number of smaller and larger elements - JavaScript
- Python - Ways to format elements of given list
- Find sum of frequency of given elements in the list in Python
- Program to count number of elements are placed at correct position in Python
- Python Program for Number of elements with odd factors in the given range
- Program to find the kth missing number from a list of elements in Python
- C# Program to return specified number of elements from the end of an array
- C# Program to return specified number of elements from the beginning of a sequence
- Sum of smaller elements of nodes in a linked list in C++
- Program to count number of elements in a list that contains odd number of digits in Python
- Python program to find sum of elements in list
- Find maximum difference between nearest left and right smaller elements in Python
- Program to find number of bit 1 in the given number in Python
- Get positive elements from given list of lists in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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−

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))

[4, 5, 9, 7, 2]

[1, 1, 2, 1, 0]

Advertisements