2724. Sort By LeetCode Solution

In this guide, you will get 2724. Sort By LeetCode Solution with the best time and space complexity. The solution to Sort By problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sort By solution in C++
  4. Sort By solution in Java
  5. Sort By solution in Python
  6. Additional Resources
2724. Sort By LeetCode Solution image

Problem Statement of Sort By

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.

Example 1:

Input: arr = [5, 4, 1, 2, 3], fn = (x) => x
Output: [1, 2, 3, 4, 5]
Explanation: fn simply returns the number passed to it so the array is sorted in ascending order.

Example 2:

Input: arr = [{“x”: 1}, {“x”: 0}, {“x”: -1}], fn = (d) => d.x
Output: [{“x”: -1}, {“x”: 0}, {“x”: 1}]
Explanation: fn returns the value for the “x” key. So the array is sorted based on that value.

Example 3:

Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]
Output: [[10, 1], [5, 2], [3, 4]]
Explanation: arr is sorted in ascending order by number at index=1.

Constraints:

arr is a valid JSON array
fn is a function that returns a number
1 <= arr.length <= 5 * 105

Complexity Analysis

  • Time Complexity: Google AdSense
  • Space Complexity: Google Analytics

2724. Sort By LeetCode Solution in C++

type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Fn = (value: JSONValue) => number;

function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] {
  arr.sort((a, b) => fn(a) - fn(b));
  return arr;
}
/* code provided by PROGIEZ */

2724. Sort By LeetCode Solution in Java

N/A
// code provided by PROGIEZ

2724. Sort By LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.