Sort By Problem
#2724
Description
LeetCode Problem 2724.
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:
arris a valid JSON arrayfnis a function that returns a number1 <= arr.length <= 5 * 10^5
Solution
Approach: Sort with a key comparator
Array.prototype.sort accepts a comparator. Since fn returns a number for each element, compare two elements by the difference of their keys: a negative result puts a first, a positive one puts b first. The problem promises the keys are distinct, so there are no ties to worry about.
Complexity: Time O(n log n) (each comparison calls fn twice), space O(1) extra besides the sort itself.
/**
* @param {Array} arr
* @param {Function} fn
* @return {Array}
*/
var sortBy = function (arr, fn) {
return arr.sort((a, b) => fn(a) - fn(b));
};