Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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]. We delete 1 (at index 5), so array becomes [4, 6, 2, 5, 3], then remove 2 (at index 2), array becomes [4, 6, 5, 3], then remove 3 (at index 3) to get [4, 6, 5], then remove 4 (at index 0) to get [6, 5], remove 5 (at index 1) to get [6], and finally remove 6 (at index 0).
Algorithm
We use a modified merge sort to count how many elements to the right of each element are smaller. This count represents the index position after smaller elements are removed.
Steps
- Create a
largerarray to store count of larger elements to the right - Use merge sort on indices, comparing actual values from original array
- During merge, count inversions (elements that will shift positions)
- Sort pairs of (value, count) and return the counts in sorted order
Implementation
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(list(range(len(nums))))
num_larger_pairs = sorted(zip(nums, larger))
return [e[1] for e in num_larger_pairs]
# Test the function
nums = [4, 6, 2, 5, 3, 1]
result = solve(nums)
print("Input:", nums)
print("Output:", result)
Input: [4, 6, 2, 5, 3, 1] Output: [5, 2, 3, 0, 1, 0]
How It Works
The algorithm uses merge sort to count inversions. When merging, if an element from the right subarray is smaller than elements in the left subarray, those left elements will have higher indices after the smaller element is removed first.
Step-by-Step Example
For nums = [4, 6, 2, 5, 3, 1]:
- Value 1: 5 elements are larger ? index 5 after removal
- Value 2: 2 elements (4, 6) remain larger ? index 2
- Value 3: 3 elements (4, 6, 5) remain larger ? index 3
- Value 4: 0 elements remain larger ? index 0
- Value 5: 1 element (6) remains larger ? index 1
- Value 6: 0 elements remain larger ? index 0
Conclusion
This solution efficiently finds deletion order indices using merge sort with inversion counting. The algorithm runs in O(n log n) time complexity, making it optimal for large datasets.
---