beat 98.94% 🔥🔥🔥
\n\n# Intuition\nThe problem requires us to sort an array based on the frequency of its elements. If multiple elements have the same frequency, they should be s
![Screenshot 2024-07-16 133512.png](https://assets.leetcode.com/users/images/a696c4e5-e7ce-4fe7-8361-00b2ecef2389_1721727034.0712757.png)\n\n# Intuition\nThe problem requires us to sort an array based on the frequency of its elements. If multiple elements have the same frequency, they should be sorted in decreasing order. The goal is to return the sorted array according to these rules.\n\n# Approach\n1. **Count Frequencies**: Use a `Map` to count the frequency of each element in the array.\n2. **Create Sort Criteria**: Convert the `Map` to an array of key-value pairs, where each pair contains an element and its frequency. Define a comparison function that sorts primarily by frequency in increasing order, and secondarily by the element value in decreasing order when frequencies are equal.\n3. **Sort Elements**: Sort the array of key-value pairs using the comparison function.\n4. **Construct Result**: Iterate through the sorted array and construct the result array by appending each element according to its frequency.\n\n# Complexity\n- Time complexity: \n  The time complexity is \\(O(n \\log n)\\), where `n` is the number of elements in the array. This is due to the sorting step, which is the most time-consuming operation.\n\n- Space complexity:\n  The space complexity is \\(O(n)\\) as we need extra space to store the frequency map and the sorted result array.\n\n# Code\n```javascript\nfunction compareFn(a, b) {\n  if (a[1] === b[1]) {\n    return b[0] - a[0];\n  } \n  return a[1] - b[1];\n}\n\nvar frequencySort = function(nums) {\n   // Step 1: Count frequencies\n   let map = new Map();\n   for (let i = 0; i < nums.length; i++) {\n    if (map.has(nums[i])) {\n        map.set(nums[i], map.get(nums[i]) + 1);\n    } else {\n        map.set(nums[i], 1);\n    }\n   } \n\n   // Step 2: Convert map to array and sort\n   let arr = [...map].sort(compareFn);\n\n   // Step 3: Construct the result array\n   let ans = [];\n   for (let i = 0; i < arr.length; i++) {\n    for (let j = 0; j < arr[i][1]; j++) {\n        ans.push(arr[i][0]);\n    }\n   }\n\n   return ans;\n};\n```\n![b772cc9a-b8c8-45ab-941f-ac36c1900ea2_1696303869.2008665.png](https://assets.leetcode.com/users/images/806923c0-d73d-4e84-bccc-99551267a1fc_1721727054.8475757.png)\n
['JavaScript']