Given an array arr and a function fn, return a sorted array sortedArr. You can assume fn only returns numbers and those numbers determine the sort order of sortedArr. sortedArr must be sorted in ascending order by fn output.
You may assume that fn will never duplicate numbers for a given array.
Example 1:
Input: arr = [5, 4, 1, 2, 3], fn = (x) => x Output: [1, 2, 3, 4, 5] Explanation: fn simply returns the number passed to it so the array is sorted in ascending order.
Example 2:
Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
Output: [{"x": -1}, {"x": 0}, {"x": 1}]
Explanation: fn returns the value for the "x" key. So the array is sorted based on that value.
Example 3:
Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] Output: [[10, 1], [5, 2], [3, 4]] Explanation: arr is sorted in ascending order by number at index=1.
Constraints:
arr is a valid JSON arrayfn is a function that returns a number1 <= arr.length <= 5 * 105This 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.
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.
JavaScript
Java
C++
C#
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.
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.
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.
JavaScript
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.
| Approach | Complexity |
|---|---|
| Using Built-in Sort with Key Function | Time Complexity: O(n log n), where n is the length of the array, due to the sort operation. |
| Using Custom Sorting via a Map of Computed Keys | Time Complexity: O(n log n), owing to the sort operation. |
Top K Frequent Elements - Bucket Sort - Leetcode 347 - Python • NeetCode • 665,789 views views
Watch 9 more video solutions →Practice Sort By with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor