#2724
Sort By
EasySortingCustom Comparators
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(n log n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution leverages built-in sorting functions that can directly sort the array based on the output of the function fn, making it both concise and efficient.
⚙️
Algorithm
2 steps- 1Step 1: Use the built-in sort function on the array.
- 2Step 2: Pass a custom comparator that applies fn to determine the order of sorting.
solution.py2 lines
1def sortBy(arr, fn):
2 return sorted(arr, key=fn)ℹ
Complexity note: The time complexity remains O(n log n) due to sorting, but we optimize space usage by sorting in place when possible.
- 1Sorting can be customized using a function to determine order.
- 2Understanding built-in sorting mechanisms can lead to more efficient solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.