Sometimes, while participating in a competitive programming test, we can be encountered with a problem in which we require to sort a pair in opposite orders by indices. This particular article focuses on solving a problem in which we require to sort the number in descending order and then the String in increasing order. This is the type of problem which is common in the sorting of pairs. Let's discuss a way in which this can be solved.
Output :
The original list is : [('Geeks', 5), ('For', 3), ('Geeks', 6), ('Is', 5), ('Best', 7), ('For', 5), ('CS', 3)] The list after inverse sorted tuple elements : [('Best', 7), ('Geeks', 6), ('For', 5), ('Geeks', 5), ('Is', 5), ('CS', 3), ('For', 3)]
Import the heapq module.
Initialize an empty list result.
Convert the given list into a min heap using the heapify() function of the heapq module.
Extract the elements from the heap one by one using the heappop() function of the heapq module.
Append the extracted element to the result list.
Return the result list.
OutputThe original list is : [('Geeks', 5), ('For', 3), ('Geeks', 6), ('Is', 5), ('Best', 7), ('For', 5), ('CS', 3)]
The list after inverse sorted tuple elements : [('Best', 7), ('CS', 3), ('For', 3), ('For', 5), ('Geeks', 5), ('Geeks', 6), ('Is', 5)]
The time complexity of this approach is O(n log n) due to the heapification step.
The auxiliary space used is O(n) to store the result list.