795. Sort Elements of an Array by Frequency
Given an array of integers, sort the elements of the array by their frequency in descending order. If two elements have the same frequency, sort them in ascending order by value.
Example 1:
Input: arr = [1, 2, 3, 2, 4, 3, 1, 2]
Output: [2, 2, 2, 1, 1, 3, 3, 4]
Explanation:
- 2 appears 3 times, so it comes first.
- 1 appears 2 times, so it comes second.
- 3 appears 2 times, so it comes next.
- 4 appears 1 time, so it comes last.
Example 2:
Input: arr = [10, 20, 30, 10, 20, 30]
Output: [10, 10, 20, 20, 30, 30]
Explanation:
- All elements appear 2 times, so they are printed in ascending order.
Now Your Turn!
Pick the correct output for the given inputInput: arr = [4, 3, 2, 3, 1, 2, 1, 1]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ N ≤ 105
- -105 ≤ arr[i] ≤ 105