![]() |
VOOZH | about |
Often during problem solving we come across to many problems where we need to reverse sort the list. But sometimes we would also want to reverse sort another list so that the elements of are automatically shifted and remain at same index as the first list even after first list get reverse sorted. Let’s discuss certain ways in which this can be done.
Method #1 : Using sorted() + reverse + zip() + itemgetter()
Combining the three functions we can possibly achieve the task. The zip functions binds the two list together, sorted function sorts the list and itemgetter function is used to define the metrics against which we need second list to shift, in this case first list. The reverse sorting is handled by reverse.
The original list 1 is : [3, 4, 9, 1, 6] The original list 2 is : [1, 5, 3, 6, 7] The lists after integrity reverse sort : [[9, 6, 4, 3, 1], [3, 7, 5, 1, 6]]
Method #2: Using sorted() + reverse + zip() + lambda function
This method performs a similar task, each function performing a similar function, the difference is just the instead of itemgetter function, lambda function performs the task of assigning a base to sort the list, i.e the first list in this case. The reverse sorting is handled by reverse.
The original list 1 is : [3, 4, 9, 1, 6] The original list 2 is : [1, 5, 3, 6, 7] The lists after integrity reverse sort : [[9, 6, 4, 3, 1], [3, 7, 5, 1, 6]]
Method #3: Using the numpy library to transpose the matrix
Algorithm:
The original list 1 is : [3, 4, 9, 1, 6] The original list 2 is : [1, 5, 3, 6, 7] The lists after integrity reverse sort : [[9, 6, 4, 3, 1], [3, 7, 5, 1, 6]]
Time Complexity: O(nlogn)
This is because we Created a 2D numpy array that takes O(n) time. The argsort() method takes O(nlogn) time complexity, and the reverse() method takes O(n) time complexity. Indexing an array takes O(n) time. Overall, the time complexity is O(nlogn).
Auxiliary Space: O(n)
This is because we are creating a 2D numpy array that requires O(n) space. Sorting the array takes O(n) space. Therefore, the overall space complexity is O(n).
Method #4: Using tuple,sorted,list comprehension
The original list 1 is : [3, 4, 9, 1, 6] The original list 2 is : [1, 5, 3, 6, 7] The lists after integrity reverse sort : [[9, 6, 4, 3, 1], [3, 7, 5, 1, 6]]
Time complexity: O(nlogn) where n is the length of the input lists.
Auxiliary space: O(n), where n is the length of the input lists.
Method #5: Using a for loop and a dictionary
The original list 1 is : [3, 4, 9, 1, 6] The original list 2 is : [1, 5, 3, 6, 7] The lists after integrity reverse sort : [[9, 6, 4, 3, 1], [3, 7, 5, 1, 6]]
Time complexity: O(n log n) (due to sorting)
Auxiliary space: O(n)