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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code