
Sponsored
Sponsored
This approach utilizes the built-in sorting functionality available in most programming languages, which allows for custom sorting based on a key extracted from each element. The function fn is used to transform each element to its sorting key during the sort operation.
Time Complexity: O(n log n), where n is the length of the array, due to the sort operation.
Space Complexity: O(n), as sorted() creates a new list.
1import java
In Java, List.sort() can be used with Comparator.comparing() to sort using a key extracted by fn. This approach leverages the Java Comparator interface functionality.
This approach involves first creating a map of the computed keys from fn for all the elements in the array. These keys are then used to guide the sorting of the original array.
Time Complexity: O(n log n), owing to the sort operation.
Space Complexity: O(n), due to the additional storage in the form of key_map.
1def sort_by(arr, fn):
2 key_map = {x: fn(x) for x in arr}
3 arr.sort(key=lambda x: key_map[x])
4 return arr
5
6# Example usage
7arr = [5, 4, 1, 2, 3]
8fn = lambda x: x
9print(sort_by(arr, fn))key_map stores the result of applying fn to each element. The array is sorted based on look-up from this dictionary during the sorting phase, providing a precomputed sort key per element.