1636. Sort Array by Increasing Frequency
leetcode
Problem:
Given an array of integers `nums`, you need to sort the array in increasing order based on the frequency of the values. If there are multiple values with the same frequency, you should sort them in decreasing order.
For example, input: `nums = [1,1,2,2,2,3]` should output: `[3,1,1,2,2,2]`.
Solution Description:
To implement a solution for sorting the array by frequency, we need to:
- Count the frequency of each element in the array.
- Use a custom comparator to sort the array first by frequency in ascending order. If frequencies are the same, sort by value in descending order.
The steps to achieve this:
- Create a frequency map that tracks how many times each element appears in the array.
- Sort the array with a custom comparator that uses the frequency map; sort by frequency in ascending order and, in case of ties, by the element's value in descending order.
Time complexity is O(n log n) due to the sort operation. Space complexity is O(n) due to the additional space used by the frequency map.
Example:
Let's consider the input `nums = [1,1,2,2,2,3]`.
- Frequency map: {1: 2, 2: 3, 3: 1}
- Sorted result: [3,1,1,2,2,2]
Setup:
The initial code framework setup in modern JavaScript, including helper functions and dummy return values. We'll use simple `console.log` statements for testing and validation.
/**
* Function to sort the array by increasing frequency
* @param {number[]} nums - An array of integers
* @return {number[]} - Sorted array based on frequency and value
*/
function sortByFrequency(nums) {
// Helper log functions for testing and demonstrations
const log = typeof NestedInteger !== 'undefined' ? () => {} : console.log;
const table = typeof NestedInteger !== 'undefined' ? () => {} : console.table;
const f = {};
nums.forEach(num => {
f[num] = (f[num] || 0) + 1;
});
nums.sort((a, b) => {
if (f[a] === f[b]) {
return b - a;
}
return f[a] - f[b];
});
return nums;
}
// Test cases
const testCases = [
{ nums: [1,1,2,2,2,3], expected: [3,1,1,2,2,2]},
{ nums: [2,3,1,3,2], expected: [1,3,3,2,2] },
{ nums: [-1,1,-6,4,5,-6,1,4,1], expected: [5,-1,4,4,-6,-6,1,1,1] },
{ nums: [2,3,3,2,1], expected: [1,3,3,2,2] },
];
testCases.forEach((test, index) => {
const result = sortByFrequency(test.nums);
console.log(`Test Case ${index + 1}: ${result.join(',') === test.expected.join(',') ? 'Passed' : 'Failed'} (Expected: ${test.expected.join(',')}, Got: ${result.join(',')})`);
});