Sort By - 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.

Input & Output

Example 1 — Basic Sorting
$ Input: arr = [5, 4, 1, 2, 3], fn = x => x
Output: [1, 2, 3, 4, 5]
💡 Note: Function returns the number itself, so we sort in ascending order: 1 < 2 < 3 < 4 < 5
Example 2 — Custom Function
$ Input: arr = [5, 4, 1, 2, 3], fn = x => x * x
Output: [1, 2, 3, 4, 5]
💡 Note: Sort by squares: fn(1)=1, fn(2)=4, fn(3)=9, fn(4)=16, fn(5)=25. Still ascending order.
Example 3 — Reverse Effect
$ Input: arr = [2, 3, 1, 4], fn = x => -x
Output: [4, 3, 2, 1]
💡 Note: Sort by negative values: fn(4)=-4, fn(3)=-3, fn(2)=-2, fn(1)=-1. Ascending by fn gives [4,3,2,1].

Constraints

  • 1 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000
  • fn returns a number for every arr[i]
  • fn will not return duplicate numbers for a given array

Visualization

Tap to expand
Sort By - Transform Then Sort INPUT Original Array (arr): 5 4 1 2 3 Transform Function (fn): fn = x => x Identity function: returns the value itself Input Values: arr = [5, 4, 1, 2, 3] fn = x => x Sort ascending by fn output ALGORITHM STEPS 1 Apply fn to each element fn(5)=5, fn(4)=4, fn(1)=1... 2 Create value-key pairs [(5,5), (4,4), (1,1), (2,2), (3,3)] 3 Sort by fn output Compare fn(a) - fn(b) 4 Return sorted array Extract original values Sorting Process: [5,4,1,2,3] --> apply fn [5,4,1,2,3] --> sort keys [1,2,3,4,5] --> sorted! Time: O(n log n) FINAL RESULT Sorted Array (sortedArr): 1 2 3 4 5 [0] [1] [2] [3] [4] Output: [1, 2, 3, 4, 5] OK - Sorted! Verification: fn(1)=1 < fn(2)=2 < fn(3)=3 < fn(4)=4 < fn(5)=5 Ascending order confirmed Key Insight: The "Transform Then Sort" approach uses JavaScript's built-in sort() with a custom comparator. Instead of comparing elements directly, we compare fn(a) - fn(b) to sort by transformed values. arr.sort((a, b) => fn(a) - fn(b)) // Returns array sorted by fn output in ascending order TutorialsPoint - Sort By | Transform Then Sort Approach
Asked in
Google 42 Amazon 38 Microsoft 31 Apple 25
34.6K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen