- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 get indices of a list after deleting elements in ascending order in Python
Suppose we have a list of distinct values and we want to remove each number in non-decreasing order. We have to find the indices of numbers in order of their deletion.
So, if the input is like nums = [4, 6, 2, 5, 3, 1], then the output will be [5, 2, 3, 0, 1, 0] as we delete 1, so array is [4, 6, 2, 5, 3], then remove 2, array is [4, 6, 5, 3], then remove 3 we get [4, 6, 5], then remove 4 we get [6, 5], remove 5, [6] and finally remove 6.
To solve this, we will follow these steps −
- Define a function my_sort() . This will take inds
- if size of inds <= 1, then
- return inds
- sorted_inds := a new list
- mid := size of inds / 2
- left := my_sort(inds[from index 0 to mid]), right := my_sort(inds[from index mid to end])
- i := 0, j := 0
- while i < size of left and j < size of right, do
- if nums[left[i]] < nums[right[j]], then
- insert left[i] at the end of sorted_inds
- i := i + 1
- otherwise,
- insert right[j] at the end of sorted_inds
- larger[right[j]] := larger[right[j]] + size of left - i
- j := j + 1
- if nums[left[i]] < nums[right[j]], then
- insert left[from index i to end] into sorted_inds
- insert right[from index j to end] into sorted_inds
- return sorted_inds
- From the main method do the following −
- larger := a new list of size nums and fill with 0
- my_sort(range 0 to size of nums)
- num_larger_pairs := make pair for each (nums, larger) and sort them
- return a list with e[1] for all e in num_larger_pairs
Example (Python)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): return solve(nums) def solve(nums): def my_sort(inds): if len(inds) <= 1: return inds sorted_inds = [] mid = len(inds) // 2 left, right = my_sort(inds[:mid]), my_sort(inds[mid:]) i = j = 0 while i < len(left) and j < len(right): if nums[left[i]] < nums[right[j]]: sorted_inds.append(left[i]) i += 1 else: sorted_inds.append(right[j]) larger[right[j]] += len(left) - i j += 1 sorted_inds.extend(left[i:]) sorted_inds.extend(right[j:]) return sorted_inds larger = [0] * len(nums) my_sort(range(len(nums))) num_larger_pairs = sorted(zip(nums, larger)) return [e[1] for e in num_larger_pairs] ob = Solution() nums = [4, 6, 2, 5, 3, 1] print(ob.solve(nums))
Input
[4, 6, 2, 5, 3, 1]
Output
[5, 2, 3, 0, 1, 0]
Advertisements