Problem Description
Given an array arr and a function fn that returns numbers, return a new array sortedArr where arr is sorted in ascending order based on the value returned by applying fn to each element. It is guaranteed that for each element in arr, fn produces a unique number.
Key Insights
- We need to sort based on a computed key from each element using the provided function.
- Since fn returns unique numbers for each element, there are no collisions in the key values.
- A simple sort with a custom comparator (that compares fn output) will solve the problem.
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting algorithm. Space Complexity: O(n) if using a sort implementation that requires extra space for sorting; otherwise O(1) for in-place sorts.
Solution
The solution involves sorting the array by using the output of the function fn on each element as the key. This is done by:
- Evaluating fn(element) for each element during the comparison in sorting.
- Leveraging built-in sorting functions that accept a custom comparator or key extractor.
- Ensuring the sorted order is ascending based on fn(element). In Python, this can be achieved with the sorted() function and its key parameter. In JavaScript, we use the Array.sort() method with a comparator that subtracts fn(a) from fn(b). The C++ and Java solutions follow a similar strategy with lambdas and custom comparators respectively.