
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.
1def
This solution makes use of Python's sorted() function, which accepts a key parameter. The key parameter is provided with the function fn, such that each element is processed through this function to determine the sorting order.
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.
1function sortBy(arr, fn) {
2 const keyMap = new Map(arr.map(x => [x, fn(x)]));
3 return arr.sort((a, b) => keyMap.get(a) - keyMap.get(b));
4}
5
6// Example usage:
7const arr = [5, 4, 1, 2, 3];
8const fn = x => x;
9console.log(sortBy(arr, fn));A Map is created from the array with keys as elements and values as precomputed results from the function fn. Sorting is carried out using these precomputed keys.