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: Custom Function OrderingOriginal Array54123Function: fn(x) = x²2516149Sort by fn values: 1 < 4 < 9 < 16 < 25Sorted Result123451² = 1 (smallest)2² = 4 (second)Elements reordered by their function values!
Understanding the Visualization
1
Input
Array [5,4,1,2,3] with function fn(x) = x²
2
Transform
Calculate fn for each: [25,16,1,4,9]
3
Sort
Sort by fn values: [1,4,9,16,25] → [1,2,3,4,5]
Key Takeaway
🎯 Key Insight: Sort elements by their transformed values, not their original values
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