Talentd
FleetCode
Make and follow sheets.Sign in

Sort By solution and explanation

Easy5 min read82.8% acceptanceUpdated 9 Apr 2026
Sort By | Leetcode 2724 | JSON | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 5:52 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. Sort By | Leetcode 2724 | JSON | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 5:52 · 1K views
  2. #day24 |2724. Sort By | 30 Days of JavaScript | Leetcode-2724| 30 Days Challenge|Array| sort() in JSCoding with Ankita · 7:41 · 854 views
  3. 🔥 Be a LeetCode LEGEND: JavaScript SORT Your Way to SUCCESS with LeetCode 2724! 💥Parul S · 7:37 · 410 views
  4. 🚀 Day 1: JavaScript Sorting Trick! | LeetCode 2724 - Sort By | 7-Day Coding ChallengeHarshada Builds & Solves · 2:22 · 113 views
  5. #Leetcode 2724 Array sortBy 🚀 Day 24 👨‍💻 30Days of JavaScript Challenge LeetCodeRajat Talesra · 2:58 · 108 views
  6. #2724 Sort By | Sort in Arrays | 30 Days of JavaScript | #javascript #leetcodesolution #arrayProgrammers choice · 5:20 · 77 views
  7. LeetCode 2724: Sort By | JavaScript Solution with Full ExplanationCode Cafe99 · 9:30 · 29 views
  8. Day 24 of My 30 Days of JavaScript Challenge — LeetCode 2724 Sort By 🔼🔽Code and Click · 2:44 · 11 views
  9. #LeetCode 2724 | Sort By #TypescriptSleepy Cracker · 1:12 · 11 views
  10. Master Array Sorting in JavaScript | LeetCode 2724 Sort By Full ExplanationMahinix · 5:45 · 6 views

The 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.

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

Approach overview

Problem Overview: You receive an array and a function fn. The task is to sort the array based on the value returned by applying fn to each element. Instead of comparing elements directly, you compare the computed keys produced by the function.

Approach 1: Using Built-in Sort with Key Function (Time: O(n log n), Space: O(1) to O(n))

The most direct solution relies on the language’s built-in sorting function. For each comparison, the algorithm applies fn(x) and fn(y) and orders the elements based on the returned values. Languages like Python provide a native key parameter, while JavaScript, Java, C++, and C# typically use a custom comparator that evaluates the function results during sorting.

The key idea is that the sorting algorithm handles ordering while your function defines the comparison rule. Internally, the algorithm performs O(n log n) comparisons, and each comparison may call the function. This makes the approach concise and easy to implement. For most interview scenarios and production code, this is the expected solution because it leverages optimized library sorting implementations.

This approach fits naturally into problems involving sorting and arrays, where you need to control ordering with a computed property.

Approach 2: Custom Sorting via a Map of Computed Keys (Time: O(n log n), Space: O(n))

Another option is to compute the key for every element once before sorting. Iterate through the array and store pairs like (fn(value), value) in a temporary structure such as a list or map. After that, sort the pairs using the precomputed key and extract the values in sorted order.

The key insight is avoiding repeated calls to fn. In some environments the sorting algorithm may evaluate the comparator many times, which can lead to redundant function executions. Precomputing the keys guarantees each element’s key is calculated exactly once. This pattern is sometimes called the “decorate-sort-undecorate” technique and commonly appears in custom comparator problems and hash map-based preprocessing.

The tradeoff is extra memory for storing the intermediate pairs. Time complexity remains O(n log n) because the array still needs to be sorted, but the function computation cost drops to O(n).

Recommended for interviews: The built-in sort with a key or comparator is what interviewers usually expect. It shows you understand how to customize sorting logic without reinventing the algorithm. Mentioning the precomputed-key optimization demonstrates deeper knowledge of how sorting repeatedly calls comparators and how to reduce redundant work.

Approach 1: Using Built-in Sort with Key Function

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.

def sort_by(arr, fn):
    return sorted(arr, key=fn)

# Example Usage:
arr = [5, 4, 1, 2, 3]
fn = lambda x: x
print(sort_by(arr, fn))
import java.util.*;

public class Main {
    public static List<Integer> sortBy(List<Integer> list, Function<Integer, Integer> fn) {
        list.sort(Comparator.comparing(fn));
        return list;
    }

    public static void main(String[] args) {
        List<Integer> arr = Arrays.asList(5, 4, 1, 2, 3);
        Function<Integer, Integer> fn = (x) -> x;
        System.out.println(sortBy(arr, fn));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> arr = {5, 4, 1, 2, 3};
    auto fn = [](int x) { return x; };

    std::sort(arr.begin(), arr.end(), [&](int a, int b) {
        return fn(a) < fn(b);
    });

    for (int num : arr) {
        std::cout << num << " ";
    }
    return 0;
}
function sortBy(arr, fn) {
    return arr.sort((a, b) => fn(a) - fn(b));
}

// Example Usage:
const arr = [5, 4, 1, 2, 3];
const fn = (x) => x;
console.log(sortBy(arr, fn));
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> arr = new List<int> {5, 4, 1, 2, 3};
        Func<int, int> fn = x => x;

        arr.Sort((a, b) => fn(a).CompareTo(fn(b)));

        foreach (int num in arr) {
            Console.Write(num + " ");
        }
    }
}

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.

Complexity

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.

Try this approach in the editor

Approach 2: Using Custom Sorting via a Map of Computed Keys

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.

def sort_by(arr, fn):
    key_map = {x: fn(x) for x in arr}
    arr.sort(key=lambda x: key_map[x])
    return arr

# Example usage
arr = [5, 4, 1, 2, 3]
fn = lambda x: x
print(sort_by(arr, fn))
function sortBy(arr, fn) {
    const keyMap = new Map(arr.map(x => [x, fn(x)]));
    return arr.sort((a, b) => keyMap.get(a) - keyMap.get(b));
}

// Example usage:
const arr = [5, 4, 1, 2, 3];
const fn = x => x;
console.log(sortBy(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.

Complexity

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.

Try this approach in the editor

Approach 3: Default Approach

function sortBy(arr: any[], fn: Function): any[] {
    return arr.sort((a, b) => fn(a) - fn(b));
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
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.
Space Complexity: O(n), as sorted() creates a new list.

Using Custom Sorting via a Map of Computed Keys

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.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Built-in Sort with Key/ComparatorO(n log n)O(1) to O(n)Default solution in most languages; concise and uses optimized library sorting
Precompute Keys (Decorate-Sort-Undecorate)O(n log n)O(n)When the key function is expensive and you want to avoid repeated evaluations

Frequently asked questions

Is Sort By easy or hard?

Sort By is considered an easy problem because it mainly tests familiarity with built-in sorting APIs and comparator functions. The main idea is applying a function to derive the sorting key rather than comparing the raw values.

How to solve Sort By in O(n)?

Achieving O(n) time is generally not possible because the task requires sorting arbitrary values, which has a lower bound of O(n log n) for comparison-based algorithms. The best optimization is precomputing fn(x) for each element in O(n) and then sorting the precomputed pairs in O(n log n).

What is the best approach for Sort By?

The most practical solution uses the language's built-in sort with a key function or custom comparator. The sorting algorithm compares elements using fn(x) and fn(y) and orders them accordingly. This runs in O(n log n) time and requires little extra code while relying on highly optimized standard library implementations.

What data structure is used in Sort By?

The core structure is an array that gets sorted using a comparator or key function. Some implementations also use an auxiliary array or map to store precomputed key-value pairs before sorting.

What is the time complexity of Sort By?

Sorting dominates the runtime. Standard comparison-based sorting algorithms run in O(n log n) time. If the key function is evaluated during comparisons, it may be called multiple times, but the overall complexity still remains O(n log n).

Sort By Python or Java solution approach

In Python, the cleanest solution uses list.sort(key=fn) or sorted(arr, key=fn). In Java, C++, C#, and JavaScript, you typically pass a custom comparator to the sort function that compares fn(a) and fn(b). All implementations maintain O(n log n) time complexity.

Is Sort By asked at Google, Amazon, or Meta?

Problems involving custom sorting and comparator logic frequently appear in interviews at large tech companies such as Google, Amazon, and Meta. While this exact problem may not always appear, the pattern of sorting based on computed keys is a common interview concept.

Comments

Now write it yourselfClose this page and solve Sort By in the editor, without looking.
Practise Sort By