Problem

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.

Examples

Example 1

1
2
3
4
5
6
7

    
    
    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

1
2
3
4
5
6
7

    
    
    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

1
2
3
4
5
6
7

    
    
    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 array
  • fn is a function that returns a number
  • 1 <= arr.length <= 5 * 10^5

Solution

Method 1 - Using Array.sort() with Custom Comparator

Intuition: Use JavaScript’s built-in sort() method with a custom comparator function that applies the given function fn to each element and compares the results.

Approach:

  1. Use the sort() method with a comparator function
  2. For each pair of elements, apply the function fn to get their sort keys
  3. Compare the sort keys to determine the order
  4. Return the sorted array

Code

1
2
3
4
5
6
7
8
/**
 * @param {Array} arr
 * @param {Function} fn
 * @return {Array}
 */
var sortBy = function(arr, fn) {
    return arr.sort((a, b) => fn(a) - fn(b));
};
1
2
3
4
5
6
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (value: JSONValue) => number;

function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] {
    return arr.sort((a, b) => fn(a) - fn(b));
}
1
2

##### C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>
#include <algorithm>
#include <functional>

template<typename T>
std::vector<T> sortBy(std::vector<T> arr, std::function<int(T)> fn) {
    std::sort(arr.begin(), arr.end(), [&fn](const T& a, const T& b) {
        return fn(a) < fn(b);
    });
    return arr;
}

// Example usage with different types
#include <iostream>
#include <string>

int main() {
    // Example 1: Sort numbers by their value
    std::vector<int> nums = {5, 4, 1, 2, 3};
    auto sortedNums = sortBy<int>(nums, [](int x) { return x; });
    
    // Example 2: Sort strings by their length
    std::vector<std::string> words = {"hello", "hi", "world"};
    auto sortedWords = sortBy<std::string>(words, [](const std::string& s) { 
        return (int)s.length(); 
    });
    
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import (
    "sort"
)

func sortBy[T any](arr []T, fn func(T) int) []T {
    result := make([]T, len(arr))
    copy(result, arr)
    
    sort.Slice(result, func(i, j int) bool {
        return fn(result[i]) < fn(result[j])
    })
    
    return result
}

// Example usage
func main() {
    // Sort integers by their value
    nums := []int{5, 4, 1, 2, 3}
    sortedNums := sortBy(nums, func(x int) int { return x })
    
    // Sort strings by their length
    words := []string{"hello", "hi", "world"}
    sortedWords := sortBy(words, func(s string) int { return len(s) })
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.*;
import java.util.function.Function;

public class Solution {
    public static <T> List<T> sortBy(List<T> arr, Function<T, Integer> fn) {
        List<T> result = new ArrayList<>(arr);
        result.sort(Comparator.comparing(fn));
        return result;
    }
    
    // Example usage
    public static void main(String[] args) {
        // Sort integers by their value
        List<Integer> nums = Arrays.asList(5, 4, 1, 2, 3);
        List<Integer> sortedNums = sortBy(nums, x -> x);
        
        // Sort strings by their length
        List<String> words = Arrays.asList("hello", "hi", "world");
        List<String> sortedWords = sortBy(words, String::length);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fun <T> sortBy(arr: List<T>, fn: (T) -> Int): List<T> {
    return arr.sortedBy { fn(it) }
}

// Example usage
fun main() {
    // Sort integers by their value
    val nums = listOf(5, 4, 1, 2, 3)
    val sortedNums = sortBy(nums) { it }
    
    // Sort strings by their length
    val words = listOf("hello", "hi", "world")
    val sortedWords = sortBy(words) { it.length }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def sort_by(arr, fn):
    """
    Sort array by applying function fn to each element.
    
    Args:
        arr: List of elements to sort
        fn: Function that takes an element and returns a number for sorting
    
    Returns:
        Sorted list in ascending order by fn output
    """
    return sorted(arr, key=fn)

# Example usage
if __name__ == "__main__":
    # Sort numbers by their value
    nums = [5, 4, 1, 2, 3]
    sorted_nums = sort_by(nums, lambda x: x)
    
    # Sort dictionaries by 'x' key
    dicts = [{"x": 1}, {"x": 0}, {"x": -1}]
    sorted_dicts = sort_by(dicts, lambda d: d["x"])
    
    # Sort arrays by second element
    arrays = [[3, 4], [5, 2], [10, 1]]
    sorted_arrays = sort_by(arrays, lambda x: x[1])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn sort_by<T, F>(mut arr: Vec<T>, f: F) -> Vec<T> 
where
    F: Fn(&T) -> i32,
{
    arr.sort_by_key(|x| f(x));
    arr
}

// Alternative that doesn't mutate original
fn sort_by_immutable<T, F>(arr: Vec<T>, f: F) -> Vec<T> 
where
    T: Clone,
    F: Fn(&T) -> i32,
{
    let mut result = arr.clone();
    result.sort_by_key(|x| f(x));
    result
}

// Example usage
fn main() {
    // Sort numbers by their value
    let nums = vec![5, 4, 1, 2, 3];
    let sorted_nums = sort_by(nums, |&x| x);
    
    // Sort strings by their length
    let words = vec!["hello".to_string(), "hi".to_string(), "world".to_string()];
    let sorted_words = sort_by(words, |s| s.len() as i32);
}

Complexity

  • ⏰ Time complexity: O(n log n) where n is the length of the array (due to the sorting operation)
  • 🧺 Space complexity: O(1) for in-place sorting, or O(n) if creating a new array