Skip to content

Commit d7de998

Browse files
Solve question with optimized approach
1 parent b3de38a commit d7de998

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Intuition
2+
Given the constraints -100 <= nums[i] <= 100, you can count the frequency of elements using an array where the index represents the value shifted by 100 (i.e., freq[x + 100] for x in nums). Then, sort it using a lambda function, which is efficient in both C++ and Python.
3+
4+
A similar concept can be applied using the Counter class in Python for a one-liner solution, which is slower but acceptable.
5+
6+
Another approach involves using counting sort, which reduces the time complexity to O(n + m).
7+
8+
Approach
9+
Count the frequency of elements using freq[x + 100] for x in nums. Sort nums with respect to the lambda function [&](int x, int y){ return (freq[x + 100] == freq[y + 100]) ? x > y : freq[x + 100] < freq[y + 100]; }.
10+
11+
The second approach uses counting sort, which is more complex compared to the simpler methods. While it has a linear time complexity, it doesn't provide significant benefits for small test cases. The best performance recorded is 2ms.
12+
13+
Complexity
14+
Time complexity:
15+
O(nlogn)
16+
Counting sort: O(n+m)
17+
18+
Space complexity:
19+
O(m) where m=max(nums)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution
2+
{
3+
public:
4+
using int2 = array<int, 2>;
5+
vector<int> frequencySort(vector<int> &nums)
6+
{
7+
int n = nums.size(), freq[201] = {0};
8+
for (int x : nums)
9+
{
10+
freq[x + 100]++;
11+
}
12+
13+
sort(nums.begin(), nums.end(), [&](int x, int y)
14+
{ return (freq[x + 100] == freq[y + 100]) ? x > y : freq[x + 100] < freq[y + 100]; });
15+
return nums;
16+
}
17+
};

0 commit comments

Comments
 (0)