question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
two-best-non-overlapping-events
2 Approaches, loop + Binary Search || Easy to understand || with Explaination
2-approaches-loop-binary-search-easy-to-ol29y
Intuition\nQuestion asked to select at most 2 events which are not colliding with each other. We can select one in first for loop and try for all other events i
RiteshHajare
NORMAL
2024-12-08T15:09:18.155062+00:00
2024-12-08T15:09:18.155103+00:00
63
false
# Intuition\nQuestion asked to select **at most 2** events which are not colliding with each other. We can select one in first for loop and try for all other events if they collide with current event, if it doesn\'t collide, we can save maximum of all answers, but this will take O(n^2) time which will lead to time limit excedded.\n\nTo reduce time complexity to O(nlogn) we can select one as previous approach but instead of searching all over the events again, we can use Binary Search, As we know binary search needs sorted array , we can sort array based on initial time.\n\nHow will sorting help based on initial time? now after sorting we can get the lower bound of event start time which is **just greater than** the end time of the selected event. So from this event which we have got by Binary search, all events ahead can have possible maximum event value, hence now we need to keep track of highest value of event till event i from event[n-1].\n\n# Approach\n- Sort all events based on initial value to compare end time of selected one with the next events start time later in binary search.\n- Compute and store the highest value of event from ith event till end event.\n- Using for loop select all events one by one and find lower bound event index which have value just greater than the current selected event.\n- Save as selectedValue + maxvalue ahead from lower bound using already computed maxValue array answer if it have greater value than previous answer.\n- It might be possible that we can\'t be getting the lower bound, so in this case it can be possible that the current event have value greater than any two other not colliding events, hence consider the individual values as well ,remember line from description **at most 2 events** \n# Complexity\n- Time complexity:\nApplying binary search(log(n)) of each element(n elements)\n=> $$O(nlogn)$$\n\n- Space complexity:\nTime taken by precompute is the only extra space taken of size n\n=> $$O(n)$$\n\n# Code\n```cpp []\n/// LOOP + Binarysearch\nclass Solution {\npublic:\n int binary(vector<vector<int>>& events,int i,int j,int curr){\n int idx = -1;\n\n while(i<=j){\n int mid = i + (j-i)/2;\n\n if(events[mid][0] > events[curr][1]){\n idx = mid;\n j = mid-1;\n }else i = mid+1;\n }\n return idx;\n }\n int maxTwoEvents(vector<vector<int>>& events) {\n int n = events.size();\n\n sort(events.begin(),events.end());\n\n vector<int>postcompute(n,0);\n\n postcompute[n-1] = events[n-1][2];\n\n for(int i=n-2;i>=0;i--)\n postcompute[i] = max(events[i][2],postcompute[i+1]);\n \n int ans = 0;\n for(int i=0;i<n;i++){\n int rightIdx = binary(events,i+1,n-1,i);\n if(rightIdx != -1)\n ans = max(ans,events[i][2]+postcompute[rightIdx]);\n \n ans = max(ans,events[i][2]);\n }\n return ans;\n }\n};\n```\n# Bonus Approach - Recursion + Memo + Binary Search\n\n```cpp []\n//Recursion + Memo + Binary Search\nclass Solution {\npublic:\n int n;\n int dp[100001][3];\n int binary(vector<vector<int>>& events,int end){\n int i=0,j=n-1,ans = n;\n while(i<=j){\n int mid = i+(j-i)/2;\n if(events[mid][0]>end){\n ans = mid;\n j = mid-1;\n }else i = mid+1;\n }\n return ans;\n }\n int solve(vector<vector<int>>& events,int i,int count){\n if(count == 2 || i>=n)\n return 0;\n if(dp[i][count]!=-1)\n return dp[i][count];\n int nextidx = binary(events,events[i][1]);\n int take = events[i][2] +solve(events,nextidx,count+1);\n int nottake = solve(events,i+1,count);\n return dp[i][count] = max(take,nottake);\n }\n int maxTwoEvents(vector<vector<int>>& events) {\n n = events.size();\n memset(dp,-1,sizeof(dp));\n sort(events.begin(),events.end());\n return solve(events,0,0);\n }\n};\n```
1
0
['Binary Search', 'Dynamic Programming', 'Sorting', 'C++']
0
two-best-non-overlapping-events
✅ Simple Java Solution
simple-java-solution-by-harsh__005-bxcx
CODE\nJava []\npublic int maxTwoEvents(int[][] events) {\n\tArrays.sort(events, (int a[], int b[])->{\n\t\tif(a[1] == b[1]){\n\t\t\treturn b[2]-a[2];\n\t\t}\n\t
Harsh__005
NORMAL
2024-12-08T13:20:00.392938+00:00
2024-12-08T13:20:00.392963+00:00
111
false
## **CODE**\n```Java []\npublic int maxTwoEvents(int[][] events) {\n\tArrays.sort(events, (int a[], int b[])->{\n\t\tif(a[1] == b[1]){\n\t\t\treturn b[2]-a[2];\n\t\t}\n\t\treturn a[1]-b[1];\n\t});\n\tint max = 0;\n\tTreeMap<Integer,Integer> map = new TreeMap<>();\n\tmap.put(0,0);\n\tfor(int[] e:events){\n\t\tint earn = e[2];\n\t\tearn += map.get(map.floorKey(e[0]-1));\n\t\t// System.out.println(e[0]+" "+e[1]+" "+e[2]);\n\t\tif(map.get(map.floorKey(e[1])) < e[2]){\n\t\t\tmap.put(e[1], e[2]);\n\t\t}\n\t\t// System.out.println(map);\n\t\tmax = Math.max(earn, max);\n\t\t// System.out.println(max);\n\t}\n\treturn max;\n}\n```
1
0
['Java']
1
two-best-non-overlapping-events
Golang Easy solutions
golang-easy-solutions-by-tarunnahak-utqk
\n\n# Code\ngolang []\nimport (\n\t"sort"\n)\n\nfunc maxTwoEvents(events [][]int) int {\n\t// Step 1: Sort events by their end times\n\tsort.Slice(events, func(
Tarunnahak
NORMAL
2024-12-08T13:13:22.168125+00:00
2024-12-08T13:13:22.168168+00:00
32
false
\n\n# Code\n```golang []\nimport (\n\t"sort"\n)\n\nfunc maxTwoEvents(events [][]int) int {\n\t// Step 1: Sort events by their end times\n\tsort.Slice(events, func(i, j int) bool {\n\t\treturn events[i][1] < events[j][1]\n\t})\n\n\tn := len(events)\n\tmaxValues := make([]int, n)\n\tmaxValues[0] = events[0][2] // Value of the first event\n\n\t// Fill the running max array\n\tfor i := 1; i < n; i++ {\n\t\tmaxValues[i] = max(maxValues[i-1], events[i][2])\n\t}\n\n\tmaxSum := 0\n\n\t// Step 3: Iterate through the events and use binary search\n\tfor i := 0; i < n; i++ {\n\t\tstart := events[i][0]\n\t\tvalue := events[i][2]\n\n\t\t// Find the latest event that ends before the current event starts\n\t\tidx := binarySearch(events, start-1)\n\n\t\tcurrentSum := value\n\t\tif idx != -1 {\n\t\t\tcurrentSum += maxValues[idx]\n\t\t}\n\n\t\tmaxSum = max(maxSum, currentSum)\n\t}\n\n\treturn maxSum\n}\n\n// Helper: Binary search to find the latest event that ends <= targetEnd\nfunc binarySearch(events [][]int, targetEnd int) int {\n\tstart, end, res := 0, len(events)-1, -1\n\n\tfor start <= end {\n\t\tmid := start + (end-start)/2\n\t\tif events[mid][1] <= targetEnd {\n\t\t\tres = mid\n\t\t\tstart = mid + 1\n\t\t} else {\n\t\t\tend = mid - 1\n\t\t}\n\t}\n\n\treturn res\n}\n\n// Utility: Max function\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n```
1
0
['Go']
0
two-best-non-overlapping-events
🏆 Binary Search & Max Value Tracking || ~25ms in Rust & Go || Brief and Clear Description
binary-search-max-value-tracking-25ms-in-wylz
\uD83D\uDE07 Intuition\n\nTo maximize the sum of values from two non-overlapping events, we leverage the sorted order of events by $end\_time$ to efficiently fi
rutsh
NORMAL
2024-12-08T13:08:37.260737+00:00
2024-12-08T13:11:21.073537+00:00
21
false
# \uD83D\uDE07 Intuition\n\nTo maximize the sum of values from two non-overlapping events, we leverage the sorted order of events by $end\\_time$ to efficiently find the best candidate for the second event using binary search. Sorting helps us ensure __efficient lookup__ for compatible events, while a __right-to-left max-value array__ keeps track of the best values for subsequent choices.\n\n# \uD83D\uDEE0\uFE0F Approach\n\n1. __Sort Events:__ Sort events by $end\\_time$ in <ins>descending order</ins> to facilitate binary search for the first compatible event.\n2. __Precompute Maximum Values:__ Use a $max\\_vals$ array to store the maximum value achievable for all events to the right of the <ins>current event</ins>.\n3. __Iterate and Search:__\n - For each event, compute the value if it\u2019s chosen as the first event.\n - Use <ins>binary search</ins> to find the first event that ends before this event starts.\n - Combine the values of these two events and update the $best$ result.\n\n# Complexity\n- __\u23F1\uFE0F Time Complexity__\n - <ins>Sorting</ins>: $O(n\\ log\u2061n)$, where $n$ is the number of events.\n - <ins>Binary Search</ins> for Each Event: $O(n\\ log\u2061n)$.\n - <ins>Total</ins>: $O(n\\ log\u2061n)$.\n\n- __\uD83D\uDEE0\uFE0F Space Complexity__\n - <ins>Extra Space</ins> for $max\\_vals$: $O(n)$.\n - <ins>In-place Sorting</ins>: $O(1)$\n\n# Code\n```rust []\nimpl Solution {\n pub fn max_two_events(events: Vec<Vec<i32>>) -> i32 {\n let mut events = events;\n\n // Sort events by end time in descending order\n events.sort_by(|a, b| b[1].cmp(&a[1]));\n\n let n = events.len();\n let mut max_vals = vec![0; n + 1]; // To store max values from right to left\n\n // Populate max_vals array with maximum values from right to left\n for i in (0..n).rev() {\n max_vals[i] = max_vals[i + 1].max(events[i][2]);\n }\n\n let mut best = 0;\n\n // Iterate over each event to find the best combination\n for i in 0..n {\n let current_value = events[i][2];\n\n // Binary search for the first event that ends before the current event starts\n let end_time = events[i][0] - 1;\n let idx = events.binary_search_by(|event| end_time.cmp(&event[1]))\n .unwrap_or_else(|x| x);\n\n let total_value = if idx < n { current_value + max_vals[idx] } else { current_value };\n\n // Update the best value\n best = best.max(total_value);\n }\n\n best\n }\n}\n```\n``` Go []\nimport (\n "sort"\n)\n\nfunc maxTwoEvents(events [][]int) int {\n // Sort events by end time in descending order\n sort.Slice(events, func(i, j int) bool {\n return events[i][1] > events[j][1]\n })\n\n n := len(events)\n maxVals := make([]int, n+1) // To store max values from the end to the beginning\n maxVals[n] = 0 // Initialize the value after the last event as 0\n\n // Populate maxVals array with maximum values from right to left\n for i := n - 1; i >= 0; i-- {\n maxVals[i] = max(maxVals[i+1], events[i][2])\n }\n\n best := 0\n\n // Iterate over each event to find the best combination\n for i := 0; i < n; i++ {\n currentValue := events[i][2]\n // Binary search for the first event that ends before the current event starts\n idx := sort.Search(n, func(j int) bool {\n return events[j][1] < events[i][0]\n })\n if idx < n {\n currentValue += maxVals[idx]\n }\n best = max(best, currentValue)\n }\n\n return best\n}\n\n// max is a helper function to find the maximum of two integers.\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n```
1
0
['Array', 'Binary Search', 'Go', 'Rust']
0
two-best-non-overlapping-events
GO | Binary Search On End Date
go-binary-search-on-end-date-by-2107mohi-bw41
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
2107mohitverma
NORMAL
2024-12-08T12:43:43.031277+00:00
2024-12-08T12:43:43.031316+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc maxTwoEvents(events [][]int) int {\n\tlength := len(events)\n\tsort.Slice(events, func(i, j int) bool {\n\t\treturn events[i][0] < events[j][0]\n\t})\n\n\tmaxValueAtIndex := make([]int, length)\n\tmaxValue := math.MinInt32\n\tfor idx := length - 1; idx >= 0; idx-- {\n\t\tmaxValue = max(maxValue, events[idx][2])\n\t\tmaxValueAtIndex[idx] = maxValue\n\t}\n\n\tmaxSum := 0\n\tfor idx := 0; idx < length; idx++ {\n\t\tcurrEventEnd := events[idx][1]\n\t\tcurrEventValue := events[idx][2]\n\n\t\tnextEventStart := currEventEnd + 1\n\t\tnextEventIndex := binarSearch(nextEventStart, events)\n\n\t\tcurrSum := currEventValue\n\t\tif nextEventIndex < length {\n\t\t\tcurrSum += maxValueAtIndex[nextEventIndex]\n\t\t}\n\t\tmaxSum = max(maxSum, currSum)\n\t}\n\n\treturn maxSum\n}\n\nfunc binarSearch(val int, arr [][]int) int {\n\tlow, high := 0, len(arr)-1\n\n\tresultIndex := high + 1\n\tfor low <= high {\n\t\tmid := low + ((high - low) / 2)\n\t\tif arr[mid][0] >= val {\n\t\t\tresultIndex = mid\n\t\t\thigh = mid - 1\n\t\t} else if arr[mid][0] < val {\n\t\t\tlow = mid + 1\n\t\t}\n\t}\n\n\treturn resultIndex\n}\n```
1
0
['Go']
0
two-best-non-overlapping-events
Easy simple intutive solution 💯🧠⚡ || C++
easy-simple-intutive-solution-c-by-srimu-p2q3
Approach\n Describe your approach to solving the problem. \nFirst sort the events based on their start time and then store the sorted start times in a seperate
srimukheshsuru
NORMAL
2024-12-08T12:13:09.483033+00:00
2024-12-08T12:13:09.483064+00:00
113
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst sort the events based on their start time and then store the sorted start times in a seperate array where you can do a binary search on. Then create a suffix array which $$i^\\text{th}$$ value stores the maximum value whose start time is greater than or equal to start time of the $$i^\\text{th}$$ event, Then for every event do a binary search on the start times array and find the event after which the events are not intresecting ```zui``` , then the possible value by the current event is ```events[i][2]+maxis[zui]``` then the aim is to maximise this value , so we can iterate over all the events and do it.The other possible case is selecting a single event conisider this and do in a simple for loop. The final maximum possible value is stored in ```ans```\n\n# Complexity\n- Time complexity:$$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxTwoEvents(vector<vector<int>>& events) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n \n int n = events.size();\n sort(events.begin(),events.end());\n int ans = INT_MIN;\n vector<int>st(n);\n for(int i=0;i<n;i++){\n st[i] = events[i][0];\n }\n vector<int> maxis(n);\n maxis[n-1] = events[n-1][2];\n for(int i=n-2;i>=0;i--){\n maxis[i] = max(maxis[i+1],events[i][2]);\n }\n for(int i=0;i<events.size();i++){\n int zui = upper_bound(st.begin(),st.end(),events[i][1])-st.begin();\n if(zui == n){\n continue;\n }\n ans = max(ans,events[i][2]+maxis[zui]);\n }\n for(int i=0;i<n;i++){\n ans = max(ans,events[i][2]);\n }\n return ans;\n }\n};\n```
1
0
['Array', 'Binary Search', 'Dynamic Programming', 'Sorting', 'C++']
1
two-best-non-overlapping-events
Kotlin | Rust
kotlin-rust-by-samoylenkodmitry-r8wr
\n\nhttps://youtu.be/uBoGo4P9t9E\n\n#### Join me on Telegram\n\nhttps://t.me/leetcode_daily_unstoppable/826\n\n#### Problem TLDR\n\nMax two non-overlapping inte
SamoylenkoDmitry
NORMAL
2024-12-08T10:11:10.590244+00:00
2024-12-08T10:11:23.413669+00:00
40
false
![1.webp](https://assets.leetcode.com/users/images/ddd2dd97-d639-4dae-a7ba-1553e860eb4b_1733652547.5224376.webp)\n\nhttps://youtu.be/uBoGo4P9t9E\n\n#### Join me on Telegram\n\nhttps://t.me/leetcode_daily_unstoppable/826\n\n#### Problem TLDR\n\nMax two non-overlapping intervals #medium #binary_search\n\n#### Intuition\n\nLet\'s observe some rich example and try to invent an algorithm:\n\n```j\n\n // 0123456789111\n // . 012\n // [.......7...]\n // [.3][.2] . \n // [.5][.3] . \n // [.4][.4] . \n // [.2][.6]. \n // .[.1][.7] \n // .. . . \n // t. . . t=3, v=3 maxV=3 maxT=3 \n // t . . t=4, v=5,maxV=5 maxT=4\n // .t . . t=5, v=4, \n // . t. . t=6, v=2\n // . t . t=7, v=2\n // . t . t=7, v=1\n // . .t . t=8, v=3\n // . . t . t=9, v=4\n // . . t. t=10,v=6, maxV=6, maxT=10\n // . . .t t=11,v=7, maxV=7, maxT=11\n // . . . t t=12,v=7\n // 3555555677 maxV\n // *f t 5+7\n\n\n```\nSome observations:\n* for current interval we should find the maximum before it\n* we can store the maximums as we go\n* we should sort events by the `end` times\n\nAnother two approaches:\n1. use a Heap, sort by start, pop from heap all non-intersecting previous and peek a max\n2. line sweep: put starts and ends in a timeline, sort by time, compute `max` after ends, and `res` on start\n\n#### Approach\n\n* binary search approach have many subtle tricks: add (0, 0) as zero, sort also by bigger values first to make binary search work\n\n#### Complexity\n\n- Time complexity:\n$$O(nlog(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n#### Code\n\n```kotlin []\n\n fun maxTwoEvents(events: Array<IntArray>): Int {\n val pq = PriorityQueue<Pair<Int, Int>>(compareBy { it.first })\n var res = 0; var max = 0;\n for ((f, t, v) in events.sortedBy { it[0] }) {\n while (pq.size > 0 && pq.peek().first < f) \n max = max(max, pq.poll().second)\n res = max(res, max + v)\n pq += t to v\n }\n return res\n }\n\n```\n```rust []\n\n pub fn max_two_events(mut events: Vec<Vec<i32>>) -> i32 {\n let (mut res, mut m) = (0, vec![(0, 0)]);\n events.sort_unstable_by_key(|e| (e[1], -e[2]));\n for e in events {\n let i = m.partition_point(|x| x.1 < e[0]) - 1;\n m.push((m.last().unwrap().0.max(e[2]), e[1]));\n res = res.max(m[i].0 + e[2]);\n }; res\n }\n\n```\n```c++ []\n\n int maxTwoEvents(vector<vector<int>>& events) {\n vector<tuple<int, int, int>> t; int res = 0, m = 0;\n for (auto e: events)\n t.push_back({e[0], 1, e[2]}),\n t.push_back({e[1] + 1, 0, e[2]});\n sort(begin(t), end(t));\n for (auto [x, start, v]: t)\n start ? res = max(res, m + v) : m = max(m, v);\n return res;\n }\n\n```
1
0
['Binary Search', 'Line Sweep', 'Heap (Priority Queue)', 'C++', 'Rust', 'Kotlin']
0
two-best-non-overlapping-events
Easy Explanation for Binary Search || C++
easy-explanation-for-binary-search-c-by-5rbdd
Intuition\nFind the maximum Value of two non-overlapping events\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. We know that if
sachin_rayal
NORMAL
2024-12-08T10:11:04.421749+00:00
2024-12-08T10:11:04.421771+00:00
8
false
# Intuition\nFind the **maximum Value** of two non-overlapping events\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We know that if `event i` end before `event j`, then every `event n` that ended before `event i-1` is also ended.\n2. For that we sort the `events` on the bases of there `endTime`.\n3. Since `event i` is already ended and is not overlapping with `event j` we take the maximum `value` from the `events` happened till the starting of `event j`.\n4. For that we made a array `dp` storing the maxValue that appered till index `i`\n5. Now we need to check one by one from index `0` to index `i-1` if there exist an event thats not overlapping with index `i` and to do it faster we do BinarySearch\n6. Changing the maxElement if we found any\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n.logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxTwoEvents(vector<vector<int>>& events) {\n sort(events.begin(),events.end(), [](const vector<int>& a,const vector<int>& b){\n return a[1]<b[1];\n }); // Increasing endTime order\n\n int maxElement = 0;\n vector<int> dp(events.size(),0);\n for(int i=0;i<events.size();i++){\n maxSingle = max(maxSingle,events[i][2]);\n dp[i]=maxSingle;\n }\n\nmaxElement = 0;\n\n for(int i=0;i<events.size();i++){\n int left = 0;\n int right = i-1;\n\n int sum = 0;\n while(left<=right){\n int mid=(right+left)/2;\n if(events[mid][1]<events[i][0]){\n sum = max(sum,dp[mid]);\n left=mid+1;\n }else{ right=mid-1;}\n }\n sum+=events[i][2];\n maxElement = max(maxElement,sum);\n }\n return maxElement;\n }\n};\n```
1
0
['Binary Search', 'C++']
0
two-best-non-overlapping-events
[Kotlin] Two sorts - simple and short
kotlin-two-sorts-simple-and-short-by-sil-9vlu
Approach\nUse two sorted arrays - one by end time, the other by by value (highest first).\n\nThen, we iterate through the events sorted by end time. We keep an
silyevsk
NORMAL
2024-12-08T09:28:21.306658+00:00
2024-12-08T09:28:21.306685+00:00
12
false
# Approach\nUse two sorted arrays - one by end time, the other by by value (highest first).\n\nThen, we iterate through the events sorted by end time. We keep an index pointing to the current element in the events sorted by value, advancing it to the highest possible event not overlapping with the events iterated over so far.\n\n# Complexity\n- Time complexity: $$O(n \u22C5 log(n))$$\n- Space complexity: $$(O(n))$$\n\n# Code\n```kotlin []\nclass Solution {\n fun maxTwoEvents(events: Array<IntArray>): Int {\n val sortedByEnd = events.sortedBy {it[1]}\n val sortedByValue = events.sortedBy {-it[2]}\n var ans = 0\n var i = 0\n for (a in sortedByEnd) {\n ans = maxOf(ans, a[2])\n while (i < sortedByValue.size && sortedByValue[i][0] <= a[1]) i++\n if (i < sortedByEnd.size) ans = maxOf(ans, a[2] + sortedByValue[i][2])\n }\n return ans\n }\n}\n```
1
0
['Kotlin']
0
two-best-non-overlapping-events
Sorting two times - view data in the different ways
sorting-two-times-view-data-in-the-diffe-ep94
Intuition\nTo maximize the selection of two non-overlapping events, we can sort the events in two different ways:\n- Sort by Increasing End Time: This allows us
luudanhhieu
NORMAL
2024-12-08T08:13:57.324304+00:00
2024-12-08T08:13:57.324328+00:00
19
false
# Intuition\nTo maximize the selection of two non-overlapping events, we can sort the events in two different ways:\n- Sort by Increasing End Time: This allows us to find the maximum value for a specific end time.\n- Sort by Decreasing Start Time: This helps us determine the maximum value for a specific start time.\nBy comparing the results from these two sorted lists, we can identify the maximum overall result.\n\n# Complexity\n\nTime Complexity: O(N log N) ?\nSpace Complexity: O(1) ?\n\n# Code\n```golang []\n\nfunc maxTwoEvents(events [][]int) int {\n\tsort.Slice(events, func(i, j int) bool {\n\t\treturn events[i][1] < events[j][1]\n\t})\n\n\tr1Max := [][]int{{events[0][1], events[0][2]}}\n\tfor i := 1; i < len(events); i++ {\n\t\tif events[i][1] == r1Max[len(r1Max)-1][0] {\n\t\t\tr1Max[len(r1Max)-1][1] = max(events[i][2], r1Max[len(r1Max)-1][1])\n\t\t} else if events[i][2] > r1Max[len(r1Max)-1][1] {\n\t\t\tr1Max = append(r1Max, []int{events[i][1], events[i][2]})\n\t\t}\n\t}\n\tsort.Slice(events, func(i, j int) bool {\n\t\treturn events[i][0] > events[j][0]\n\t})\n\tr2Min := [][]int{{events[0][0], events[0][2]}}\n\tfor i := 1; i < len(events); i++ {\n\t\tif events[i][0] == r2Min[len(r2Min)-1][0] {\n\t\t\tr2Min[len(r2Min)-1][1] = max(events[i][2], r2Min[len(r2Min)-1][1])\n\t\t} else if events[i][2] > r2Min[len(r2Min)-1][1] {\n\t\t\tr2Min = append(r2Min, []int{events[i][0], events[i][2]})\n\t\t}\n\t}\n\tmax := 0\n\tfor i := 0; i < len(r1Max); i++ {\n\t\tif max < r1Max[i][1] {\n\t\t\tmax = r1Max[i][1]\n\t\t}\n\t\tfor j := 0; j < len(r2Min); j++ {\n\t\t\tif r2Min[j][0] <= r1Max[i][0] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif r1Max[i][1]+r2Min[j][1] > max {\n\t\t\t\tmax = r1Max[i][1] + r2Min[j][1]\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}\n```
1
0
['Go']
0
two-best-non-overlapping-events
Easy C++ Solution ⭐||Explanation✔|| Beats 93.24%🎯|| PLEASE UPVOTE ⬆
easy-c-solution-explanation-beats-9324-p-6dam
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to maximize the sum of values by attending at most two non-overlapping even
Abhijithsr13
NORMAL
2024-12-08T08:04:31.763542+00:00
2024-12-08T08:04:31.763573+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to maximize the sum of values by attending at most two non-overlapping events. The problem boils down to efficiently finding the best combination of two events where one event ends before the other starts. Sorting the events by their end times and using binary search to locate the last non-overlapping event ensures we can solve the problem efficiently.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n#### 1. Sorting the Events:\n\n- First, sort the events by their end time. This allows us to efficiently find the latest non-overlapping event for any given event using binary search.\n#### 2. Precomputing Maximum Values:\n\n- Precompute an array ***maxUpTo*** where ***maxUpTo[i]*** represents the maximum value of any single event from the start up to the ***ith*** event.\n- This helps in efficiently calculating the sum of the current event\'s value with the best non-overlapping event.\n#### 3. Finding Non-Overlapping Events:\n\n- For each event i, use binary search to find the last event j such that the end time of event j is less than the start time of event i.\n- Add the value of event i to the best value up to j **(i.e., maxUpTo[j])**.\n#### 4. Updating the Maximum Value:\n\n- Track the maximum value obtained by attending either a single event or a combination of two non-overlapping events.\n#### 5. Return the Result:\n\n- The result is the maximum value obtained by considering all events.\n\n# Complexity\n- Time complexity:**O(nlogn)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxTwoEvents(vector<vector<int>>& events) {\n sort(events.begin(), events.end(), [](const vector<int>& a, const vector<int>& b) {\n return a[1] < b[1];\n });\n\n int n = events.size();\n vector<int> maxUpTo(n, 0); // Maximum value up to each event\n int maxValue = 0;\n\n // Precompute maxUpTo\n maxUpTo[0] = events[0][2];\n for (int i = 1; i < n; ++i) {\n maxUpTo[i] = max(maxUpTo[i - 1], events[i][2]);\n }\n\n // Iterate over each event and compute the maximum value\n for (int i = 0; i < n; ++i) {\n int currValue = events[i][2];\n\n // Find the latest non-overlapping event using binary search\n int left = 0, right = i - 1, idx = -1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (events[mid][1] < events[i][0]) {\n idx = mid;\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n // Add the value of the best non-overlapping event\n if (idx != -1) {\n currValue += maxUpTo[idx];\n }\n\n // Update the maximum value\n maxValue = max(maxValue, currValue);\n }\n\n return maxValue;\n }\n};\n```
1
0
['Array', 'Binary Search', 'Dynamic Programming', 'Sorting', 'Heap (Priority Queue)', 'C++']
0
sort-array-by-increasing-frequency
Python 3 solution - with process of thinking and improvement
python-3-solution-with-process-of-thinki-7ruf
Part 1\n\nSunday morning, Spotify, coffee, console... Task from the list of tasks to solve later.\nLet\'s go!\n\npython\n~ \u276F python3
denisrasulev
NORMAL
2021-02-14T12:14:17.303649+00:00
2021-02-14T12:15:52.403446+00:00
19,938
false
# Part 1\n\nSunday morning, Spotify, coffee, console... Task from the list of tasks to solve later.\nLet\'s go!\n\n```python\n~ \u276F python3 at 10:38:03\nPython 3.9.1 (default, Feb 3 2021, 07:38:02)\n[Clang 12.0.0 (clang-1200.0.32.29)] on darwin\nType "help", "copyright", "credits" or "license" for more information.\n>>> nums = [1,1,2,2,2,6,6,4,4,5,5,3]\n```\n\nOk, so I need to count frequency of each of the unique values... First idea - use `Counter`. This returns `collection` type of object:\n\n```python\n>>> d = Counter(nums)\n>>> d\nCounter({2: 3, 1: 2, 6: 2, 4: 2, 5: 2, 3: 1})\n>>> type(d)\n<class \'collections.Counter\'>\n```\n\nNow I need to sort those values following the requirements in the description. \'Counter\' object has no attribute \'sort\', and \'sorted\' will only sort values, not frequencies. Googling options, found this [StackOverflow question](https://stackoverflow.com/q/20950650/4440387) with lots of useful answers. Reading... Let\'s try easier object:\n\n```python\n>>> r = Counter(nums).most_common()\n```\n\nThis returns a list of tuples, where first number is value and second - its\' frequency. Can I sort it in the same command? Jumping to the [official documentation](https://docs.python.org/3/library/collections.html#collections.Counter.most_common). Nope, not sortable in the command itself, moreover: "*Elements with equal counts are ordered in the order first encountered*". Ok, let\'s sort it directly, first by values in the decreasing order, then by frequencies in the increasing.\n\n```\n>>> r.sort(key = lambda x: x[0], reverse=True)\n>>> r.sort(key = lambda x: x[1])\n>>> r\n[(3, 1), (6, 2), (5, 2), (4, 2), (1, 2), (2, 3)]\n```\n\nLooks promising. Now I want to expand those tuples into a single list... Still browsing answers to the same [question](https://stackoverflow.com/q/20950650/4440387). Remembering that I can expand tuple and get every number from it by using this:\n\n```\n>>> a, b = (3, 2)\n>>> a\n3\n>>> b\n2\n```\n\nso then I can repeat every value by the number of its\' frequency like so:\n\n```\n>>> [3]*2\n[3, 3]\n```\n\nAha. Now I need an empty list to combine all those tuples into a single list:\n\n```\nt = []\nfor i in r:\n a, b = i\n t.extend([a] * b)\n\n>>> t\n[3, 6, 6, 5, 5, 4, 4, 1, 1, 2, 2, 2]\n```\n\nWoo-hoo! That\'s what I need. So the complete solution now looks like this:\n\n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n \n r = Counter(nums).most_common()\n r.sort(key = lambda x: x[0], reverse=True)\n r.sort(key = lambda x: x[1])\n \n t = []\n for i in r:\n a, b = i\n t.extend([a]*b)\n \n return t\n```\n\n**Result**:\nRuntime: 52 ms, faster than 63.30% of Python3 online submissions for Sort Array by Increasing Frequency.\nMemory Usage: 14.2 MB, less than 58.20% of Python3 online submissions for Sort Array by Increasing Frequency.\n\nNot the best, but the task is solved.\n\n# Part 2\n\nNow it\'s time for another *fun* - can I make it one-liner or optimize the solution in any other way?\n\nLooking at sorting lines... Can I sort it in one go? Yes! So, first we sort by values in the reverse order (`-x[0]`) and then by their frequencies (`x[1]`) in direct order. \n```\n>>> r.sort(key = lambda x: (x[1], -x[0]))\n```\n\nBasically, it\'s the same operation as the above but now coded in one line. Love Python :) Same logic applies to the tuple expansion part and it allows to save another line:\n\n```\nt = []\nfor i in r:\n\tt += ([i[0]] * i[1])\n```\n\nAnd then I thought - if I can sort by value and its\' frequency why do I need intermediate list? Can I sort the original list the same way?! Let\'s see...\n\n```python\n>>> nums\n[1, 1, 2, 2, 2, 6, 6, 4, 4, 5, 5, 3]\n>>> r = Counter(nums)\n>>> r\nCounter({2: 3, 1: 2, 6: 2, 4: 2, 5: 2, 3: 1})\n>>> nums.sort(key=lambda x: (r[x], -x))\n>>> nums\n[3, 6, 6, 5, 5, 4, 4, 1, 1, 2, 2, 2]\n```\n\nVoila! That feels sooo good. But `x.sort` makes it in-place and I need to return an object... So, I need to change it to `sorted` then:\n\n```\n>>> result = sorted(nums, key=lambda x: (r[x], -x))\n>>> result\n[3, 6, 6, 5, 5, 4, 4, 1, 1, 2, 2, 2]\n```\n\nPerfect. So the final variant would be:\n```python\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n r = Counter(nums)\n return sorted(nums, key=lambda x: (r[x], -x))\n```\n\nAnd it\'s even faster!\n\nRuntime: 44 ms, faster than 95.07% of Python3 online submissions for Sort Array by Increasing Frequency.\nMemory Usage: 14.3 MB, less than 58.20% of Python3 online submissions for Sort Array by Increasing Frequency.\n\n**NOTE**\n* If you want to downvote this post, please, be brave and comment why. This will help me and others to learn from it.\n* If you think that others can learn something from this post, then please, upvote it. Thanks.
341
2
['Python', 'Python3']
28
sort-array-by-increasing-frequency
[Java] Simple Custom Sort with Detailed Explanation!
java-simple-custom-sort-with-detailed-ex-rq4k
\npublic int[] frequencySort(int[] nums) {\n\tMap<Integer, Integer> map = new HashMap<>();\n\t// count frequency of each number\n\tArrays.stream(nums).forEach(n
jerrywusa
NORMAL
2020-10-31T18:43:01.623568+00:00
2020-10-31T18:48:41.240761+00:00
25,902
false
```\npublic int[] frequencySort(int[] nums) {\n\tMap<Integer, Integer> map = new HashMap<>();\n\t// count frequency of each number\n\tArrays.stream(nums).forEach(n -> map.put(n, map.getOrDefault(n, 0) + 1));\n\t// custom sort\n\treturn Arrays.stream(nums).boxed()\n\t\t\t.sorted((a,b) -> map.get(a) != map.get(b) ? map.get(a) - map.get(b) : b - a)\n\t\t\t.mapToInt(n -> n)\n\t\t\t.toArray();\n}\n```\n\ncustom sort explanation:\n**.stream(nums)**\niterates through the nums array\n\n**.boxed()**\nconverts each int to Integer object, this is because .sorted() can only operate on objects\n\n**.sorted((a,b) -> map.get(a) != map.get(b) ? map.get(a) - map.get(b) : b - a)**\nif frequency of two numbers are not the same, sort by ascending frequency. If frequencies are the same, sort by decending numeric value\n\n**.mapToInt(n -> n)**\nconverts Integer to int\n\n**.toArray()**\nreturns array
205
9
['Sorting', 'Java']
22
sort-array-by-increasing-frequency
✅💯🔥Explanations No One Will Give You🎓🧠Very Detailed Approach🎯🔥Extremely Simple And Effective🔥
explanations-no-one-will-give-youvery-de-nksb
\n \n \n Never limit yourself because of others\u2019 limited imagination; never limit others because of your own limited imagi
heir-of-god
NORMAL
2024-07-23T04:44:04.758338+00:00
2024-07-23T04:44:04.758366+00:00
32,794
false
<blockquote>\n <p>\n <b>\n Never limit yourself because of others\u2019 limited imagination; never limit others because of your own limited imagination\n </b> \n </p>\n <p>\n --- Mae Jemison ---\n </p>\n</blockquote>\n\n# \uD83D\uDC51Problem Explanation and Understanding:\n\n## \uD83C\uDFAF Problem Description\nYou are given an integer array `nums` and asked to sort this array by frequency of its elements first (In increasing order) and by elements theyselves second (In decreasing order).\n\n## \uD83D\uDCE5\u2935\uFE0F Input:\n- Integer array `nums`\n\n## \uD83D\uDCE4\u2934\uFE0F Output:\nArray after perfoming sorting\n\n---\n\n# 1\uFE0F\u20E3\uD83D\uDE0E Approach: Custom Sort Comparator\n\n# \uD83E\uDD14 Intuition\n- We know how to perform sorting with comparators but we need to somehow optimize getting frequency, because counting number of elements iterating through whole list for every element is quite unefficient.\n- One of your choices - hashmap, but since constraints are pretty small I would say that using array with constant space (for this problem) can help to achieve O(1) space with counting sort but since there functions for sorting (like in Python) which uses algorithms like Timsort for sorting they use extra space in their implementation O(n) \n- Using frequency counter and elements themselves we can easily sort array by creating new custom comparator and pass it to the sort function.\n- Because we can have negative values (-100 <= num <= 100) in order to find index for counter for current element we must add to this element 100 - think about it, for -100 index will be 0, for -99 index will be 1 and for 100 index will be 200 (So we need 201 elements in the array - 100 + 100 + 1 (100 negative + 100 positive + zero))\n\n# \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB Coding \n- Initializes a list `count` of size 201 with all elements set to 0.\n- Iterates over each number `num` in `nums`.\n- Increments the count of `num + 100` in the `count` list.\n- Sorts `nums` using a custom key.\n- The custom key sorts `nums` based on two criteria: the frequency of each number (increasing order) and the value of the number itself (decreasing order if frequencies are the same).\n- Returns the sorted `nums` list.\n\n# \uD83D\uDCD7 Complexity Analysis\n- \u23F0 Time complexity: O(n * log n), since we use built-in sort functions which is n * log n for most languages\n- \uD83E\uDDFA Space complexity: O(n), since since most sort functions use extraspace up to O(n) but if we don\'t count this our implementation takes O(1) space (array always have a size of 201)\n\n# \uD83D\uDCBB Code\n``` python []\nclass Solution:\n def frequencySort(self, nums: list[int]) -> list[int]:\n count: list[int] = [0 for _ in range(201)]\n for num in nums:\n count[num + 100] += 1\n nums.sort(key=lambda val: (count[val + 100], -val))\n return nums\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n vector<int> count(201, 0);\n for (int num : nums) {\n count[num + 100]++;\n }\n sort(nums.begin(), nums.end(), [&](int a, int b) {\n if (count[a + 100] == count[b + 100])\n return a > b;\n return count[a + 100] < count[b + 100];\n });\n return nums;\n }\n};\n```\n``` JavaScript []\nfunction frequencySort(nums) {\n let count = Array(201).fill(0);\n nums.forEach(num => {\n count[num + 100]++;\n });\n return nums.sort((a, b) => {\n if (count[a + 100] === count[b + 100]) {\n return b - a;\n }\n return count[a + 100] - count[b + 100];\n });\n}\n```\n``` Java []\nclass Solution {\n public int[] frequencySort(int[] nums) {\n int[] count = new int[201];\n for (int num : nums) {\n count[num + 100]++;\n }\n Integer[] numsArr = Arrays.stream(nums).boxed().toArray(Integer[]::new);\n Arrays.sort(numsArr, (a, b) -> {\n if (count[a + 100] == count[b + 100]) {\n return b - a;\n }\n return count[a + 100] - count[b + 100];\n });\n return Arrays.stream(numsArr).mapToInt(Integer::intValue).toArray();\n }\n}\n```\n``` C []\nint compare(const void* a, const void* b, void* count) {\n int valA = *(int*)a;\n int valB = *(int*)b;\n int* cnt = (int*)count;\n\n if (cnt[valA + 100] == cnt[valB + 100]) {\n return valB - valA;\n }\n return cnt[valA + 100] - cnt[valB + 100]; \n}\n\nint* frequencySort(int* nums, int numsSize, int* returnSize) {\n int count[201] = {0};\n for (int i = 0; i < numsSize; i++) {\n count[nums[i] + 100]++;\n }\n\n qsort_r(nums, numsSize, sizeof(int), compare, count);\n\n *returnSize = numsSize;\n return nums;\n}\n```\n\n# Additional Python One-liner (Not recommend to use, it\'s slow because, I think, it creates new Counter() object for every iteration (element) and also creates new array in memory instead of using input)\n```python\nclass Solution:\n def frequencySort(self, nums: list[int]) -> list[int]:\n return sorted(nums, key=lambda val: (Counter(nums)[val], -val))\n```\n\n## \uD83D\uDCA1\uD83D\uDCA1\uD83D\uDCA1I encourage you to check out [my profile](https://leetcode.com/heir-of-god/) and [Project-S](https://github.com/Heir-of-God/Project-S) project for detailed explanations and code for different problems (not only Leetcode). Happy coding and learning!\uD83D\uDCDA\n\n### Sorry for that, but I missed the moment repository gets 25 stars\u2B50 I want to say much thanks for everyone who support me this way, you all are great, I really appreciate that, keep moving!\n\n<div align="center">\n\n![image.png](https://assets.leetcode.com/users/images/b64095d8-3f2a-49f3-93ec-c9a8c9992acf_1721708995.7374904.png)\n\n</div>\n\n### Please consider *upvote*\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F because I try really hard not just to put here my code and rewrite testcase to show that it works but explain you WHY it works and HOW. Thank you\u2764\uFE0F\n\n## If you have any doubts or questions feel free to ask them in comments. I will be glad to help you with understanding\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n\n![There is image for upvote](https://assets.leetcode.com/users/images/fde74702-a4f6-4b9f-95f2-65fa9aa79c48_1716995431.3239644.png)\n
164
28
['Array', 'Hash Table', 'C', 'Sorting', 'Counting Sort', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
15
sort-array-by-increasing-frequency
[C++/Python] Sort
cpython-sort-by-lee215-wqi6
Explanation\nSort by 2 keys.\n@v_paliy note that:\n"count[x] sorts by frequency, and if two values are equal, it will sort the keys in decreasing order."\n\n\n#
lee215
NORMAL
2020-10-31T16:16:55.155677+00:00
2020-11-01T14:14:19.689679+00:00
24,407
false
## **Explanation**\nSort by 2 keys.\n@v_paliy note that:\n"count[x] sorts by frequency, and if two values are equal, it will sort the keys in decreasing order."\n<br>\n\n## **Complexity**\nTime `O(NlogN)`\nSpace `O(N)`\n<br>\n\n**C++**\n```cpp\n vector<int> frequencySort(vector<int>& A) {\n unordered_map<int, int> count;\n for (int a: A)\n count[a]++;\n sort(begin(A), end(A), [&](int a, int b) {\n return count[a] == count[b] ? a > b : count[a] < count[b];\n });\n return A;\n }\n```\n**Python:**\n```py\n def frequencySort(self, A):\n count = collections.Counter(A)\n return sorted(A, key=lambda x: (count[x], -x))\n```\n
147
4
[]
31
sort-array-by-increasing-frequency
1-liner|count freq[x+100] & sort by lambda vs Counting sort||0ms beats 100%
1-linercount-freqx100-sort-by-lambda-vs-t99lk
Intuition\n Describe your first thoughts on how to solve this problem. \nSince the constraints -100 <= nums[i] <= 100 count freq[x+100] for x in nums\nThen sort
anwendeng
NORMAL
2024-07-23T00:30:23.702684+00:00
2024-07-23T23:55:39.377272+00:00
17,557
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the constraints `-100 <= nums[i] <= 100` count freq[x+100] for x in nums\nThen sort it by a lambda which is fast both in C++& Python. Similar concept, using Counter in python, a 1-liner is given, the 1st version for that is slow but accepted; 1 of the reivised versions is presented.\n\nLater try other approach. 2nd approach is using counting sort which reduces the time complexity to $O(n+m)$.\n\nSimilar questions solved in LC:\n[451. Sort Characters By Frequency\n](https://leetcode.com/problems/sort-characters-by-frequency/solutions/4689181/just-arrays-3-kinds-of-sortings-no-hash-table-0ms-beats-100/)[2418. Sort the People\n](https://leetcode.com/problems/sort-the-people/solutions/5513898/sort-pairs-reuse-names-1-line-pack-heightsi-iinto-an-int17ms-beats-9705/)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. count freq[x+100] for x in nums\n2. Sort nums w.r.t. the lambda function `[&](int x, int y){\n return (freq[x+100]==freq[y+100])?x>y:freq[x+100]<freq[y+100];\n }`\n3. 2nd approach uses counting sort which is harder than easy. On the other hand, its time is linear, but brings no benefit for the small sized testcases. The best record is 2ms.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$\nCounting sort: $O(n+m)$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n $$O(m)$$ where m=max(nums)-min(nums)\n# Code||C++ 0ms beats 100%\n[submitted C++code](https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330076381/)\n```C++ []\nclass Solution {\npublic:\n using int2=array<int,2>;\n vector<int> frequencySort(vector<int>& nums) {\n int n=nums.size(), freq[201]={0};\n for(int x:nums){\n freq[x+100]++;\n }\n \n sort(nums.begin(), nums.end(), [&](int x, int y){\n return (freq[x+100]==freq[y+100])?x>y:freq[x+100]<freq[y+100];\n });\n return nums;\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n```Python []\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq=[0]*201\n for x in nums:\n freq[x+100]-=1 \n return sorted(nums, key=lambda x:(freq[x+100], x), reverse=True)\n \n```\n# C++ using counting sort \n```\nclass Solution {\npublic:\n // counting sort for unique x in the decreasing order \n static void counting_sort(auto& arr) {// this simplifed version is sufficient for use\n if (arr.empty()) return;\n auto [xMin, xMax] = minmax_element(arr.begin(), arr.end());\n int m = *xMin, v = *xMax - m + 1;\n vector<bool> cnt(v, 0);\n for (int x : arr)\n cnt[x - m]=1;\n for (int y = v-1, i=0; y >= 0; y--) { //sort in decreasing order\n if (cnt[y]==0) continue;\n arr[i]=y+m;\n i++;\n }\n }\n\n static vector<int> frequencySort(vector<int>& nums) {\n const int n = nums.size();\n vector<int> freq(201, 0);\n int maxF = 0, maxX = -1;\n for (int x : nums) {\n x += 100; // x-min_x where min_x=-100\n int f = ++freq[x];\n maxX = max(x, maxX);\n maxF = max(f, maxF);\n }\n vector<vector<int>> freqx(maxF + 1);\n for (int x = 0; x <= maxX; x++) {\n if (freq[x] > 0)\n freqx[freq[x]].push_back(x-100); // Adjust value back\n }\n\n int i = 0;\n for (int f = 1; f <= maxF; f++) {\n auto& arr = freqx[f];\n counting_sort(arr);\n for (int x : arr) {// each x occurs f times\n fill(nums.begin()+i, nums.begin()+i+f, x);\n i+=f;\n }\n }\n return nums;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# C++ using counting sort||simple version 0ms beats 100%\n```\nclass Solution {\npublic:\n static vector<int> frequencySort(vector<int>& nums) {\n const int n = nums.size();\n vector<int> freq(201, 0);\n int maxF = 0, maxX = -1;\n for (int x : nums) {\n x += 100; // x-min_x where min_x=-100\n int f = ++freq[x];\n maxX = max(x, maxX);\n maxF = max(f, maxF);\n }\n vector<vector<int>> freqx(maxF + 1);\n for (int x = maxX; x >=0; x--) {\n if (freq[x] > 0)\n freqx[freq[x]].push_back(x-100); // Adjust value back\n }\n\n int i = 0;\n for (int f = 1; f <= maxF; f++) {\n auto& arr = freqx[f];\n for (int x : arr) {// each x occurs f times\n fill(nums.begin()+i, nums.begin()+i+f, x);\n i+=f;\n }\n }\n return nums;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# revised Python 1-liner||Thanks to all who posted the comments & suggestions on this issue.\n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sorted(nums, key=lambda x, K=Counter(nums):(K[x], -x))\n```
60
2
['Array', 'Hash Table', 'Sorting', 'Counting Sort', 'C++', 'Python3']
20
sort-array-by-increasing-frequency
Python solution
python-solution-by-a_bs-8gir
Code\n\nfrom collections import Counter\n\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq = Counter(nums)\n nu
20250406.A_BS
NORMAL
2024-07-23T02:43:49.796604+00:00
2024-07-23T02:43:49.796640+00:00
5,095
false
# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq = Counter(nums)\n nums.sort(key=lambda x: (freq[x], -x))\n return nums\n\n```\n### Example 1\n**Input:** `nums = [1, 1, 2, 2, 2, 3]`\n\n**Step 1: Count the frequency of each element**\n\nWe use the `Counter` from the `collections` module to count the frequency of each element in the array.\n\n```python\nfrom collections import Counter\n\nnums = [1, 1, 2, 2, 2, 3]\nfreq = Counter(nums)\nprint(freq)\n```\n\nThe output will be:\n```\nCounter({2: 3, 1: 2, 3: 1})\n```\n\nThis means:\n- The number `2` appears 3 times.\n- The number `1` appears 2 times.\n- The number `3` appears 1 time.\n\n**Step 2: Sort the array based on the frequency and value**\n\nWe need to sort the array such that:\n1. Elements with lower frequency come first.\n2. If two elements have the same frequency, the one with the higher value comes first.\n\nThe sorting key we use is `(freq[x], -x)`, where:\n- `freq[x]` ensures elements are sorted by their frequency in increasing order.\n- `-x` ensures that if frequencies are the same, elements are sorted by their value in decreasing order.\n\n```python\nnums.sort(key=lambda x: (freq[x], -x))\nprint(nums)\n```\n\nThe output will be:\n```\n[3, 1, 1, 2, 2, 2]\n```\n\n**Explanation:**\n- `3` has a frequency of 1, so it comes first.\n- `1` has a frequency of 2, so it comes next.\n- `2` has a frequency of 3, so it comes last.\n\n### Example 2\n**Input:** `nums = [2, 3, 1, 3, 2]`\n\n**Step 1: Count the frequency of each element**\n\n```python\nnums = [2, 3, 1, 3, 2]\nfreq = Counter(nums)\nprint(freq)\n```\n\nThe output will be:\n```\nCounter({2: 2, 3: 2, 1: 1})\n```\n\nThis means:\n- The number `2` appears 2 times.\n- The number `3` appears 2 times.\n- The number `1` appears 1 time.\n\n**Step 2: Sort the array based on the frequency and value**\n\n```python\nnums.sort(key=lambda x: (freq[x], -x))\nprint(nums)\n```\n\nThe output will be:\n```\n[1, 3, 3, 2, 2]\n```\n\n**Explanation:**\n- `1` has a frequency of 1, so it comes first.\n- `3` and `2` both have a frequency of 2. Since `3` is greater than `2`, `3` comes before `2`.\n\n### Example 3\n**Input:** `nums = [-1, 1, -6, 4, 5, -6, 1, 4, 1]`\n\n**Step 1: Count the frequency of each element**\n\n```python\nnums = [-1, 1, -6, 4, 5, -6, 1, 4, 1]\nfreq = Counter(nums)\nprint(freq)\n```\n\nThe output will be:\n```\nCounter({1: 3, -6: 2, 4: 2, -1: 1, 5: 1})\n```\n\nThis means:\n- The number `1` appears 3 times.\n- The number `-6` appears 2 times.\n- The number `4` appears 2 times.\n- The number `-1` appears 1 time.\n- The number `5` appears 1 time.\n\n**Step 2: Sort the array based on the frequency and value**\n\n```python\nnums.sort(key=lambda x: (freq[x], -x))\nprint(nums)\n```\n\nThe output will be:\n```\n[5, -1, 4, 4, -6, -6, 1, 1, 1]\n```\n\n**Explanation:**\n- `5` and `-1` both have a frequency of 1. Since `5` is greater than `-1`, `5` comes first.\n- `4` and `-6` both have a frequency of 2. Since `4` is greater than `-6`, `4` comes before `-6`.\n- `1` has the highest frequency of 3, so it comes last.\n\n
57
0
['Python3']
12
sort-array-by-increasing-frequency
C++ solution using maps
c-solution-using-maps-by-aparna_g-7kzn
This is question is a very slight modifictaion of https://leetcode.com/problems/sort-characters-by-frequency/\nThis is just a basic implementation :-)\n\nclass
aparna_g
NORMAL
2021-04-07T06:42:11.777280+00:00
2021-04-07T07:00:17.458777+00:00
12,415
false
This is question is a very slight modifictaion of https://leetcode.com/problems/sort-characters-by-frequency/\nThis is just a basic implementation :-)\n```\nclass Solution {\npublic:\n \n static bool cmp(pair<int,int>&a, pair<int,int>&b) {\n return (a.second==b.second) ? a.first>b.first : a.second<b.second;\n }\n \n \n vector<int> frequencySort(vector<int>& nums) {\n if(nums.size()==1) \n return nums;\n map<int,int> mp;\n for(int i=0;i<nums.size();i++) \n {\n mp[nums[i]]++;\n }\n vector<pair<int,int>> val_freq;\n for(auto m : mp) \n {\n val_freq.push_back(m);\n }\n sort(val_freq.begin(),val_freq.end(),cmp);\n vector<int> result;\n for(auto v : val_freq) {\n for(int i=0;i<v.second;i++) {\n result.push_back(v.first);\n }\n }\n return result;\n }\n};\n```\nTry this too: https://leetcode.com/problems/sort-characters-by-frequency/\nSolution: https://leetcode.com/problems/sort-characters-by-frequency/discuss/1146549/C%2B%2B-map-solution
52
1
['C', 'Sorting', 'C++']
8
sort-array-by-increasing-frequency
[Java] Sorted the Occurrence by Using Collections.sort()..
java-sorted-the-occurrence-by-using-coll-yfn2
Looks like there is no others using this in Java at this moment yet, so I post my solution here for your reference.\n\n public int[] frequencySort(int[] nums
admin007
NORMAL
2020-10-31T16:36:25.024103+00:00
2020-11-02T20:16:09.290355+00:00
8,663
false
Looks like there is no others using this in Java at this moment yet, so I post my solution here for your reference.\n```\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int num : nums) {\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n List<Map.Entry<Integer, Integer>> list = new ArrayList(map.entrySet());\n Collections.sort(list, (a,b) -> a.getValue() == b.getValue() ? b.getKey() - a.getKey() : a.getValue() - b.getValue());\n int index = 0;\n int[] res = new int[nums.length];\n for (Map.Entry<Integer, Integer> entry : list) {\n \n int count = entry.getValue();\n int key = entry.getKey();\n \n for (int i=0; i<count; i++) {\n res[index++] = key;\n }\n }\n return res;\n }\n```
49
2
[]
9
sort-array-by-increasing-frequency
Easy Solution by using map || Using inbuilt sorting technique 😎 || Solution in C++ and Java 💯✅
easy-solution-by-using-map-using-inbuilt-umna
Screenshot \uD83D\uDCC3\n\n\n\n# Intuition \uD83E\uDD14\n Describe your first thoughts on how to solve this problem. \nWe need to keep the track of numbers in n
purnimakesarwani47
NORMAL
2024-07-23T00:21:20.241547+00:00
2024-07-23T00:21:20.241576+00:00
14,085
false
# Screenshot \uD83D\uDCC3\n![image.png](https://assets.leetcode.com/users/images/307c42a2-7513-4fe5-a667-282bb82d1a53_1721693255.3984854.png)\n\n\n# Intuition \uD83E\uDD14\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to keep the track of numbers in nums that how many times it has been occured therefore we will use `MAP` data structure for storing `key` as `nums[i]` and `value` as how many times it has been occured i.e. `freq`.\n\n \n\n# Approach \uD83E\uDE9C\n<!-- Describe your approach to solving the problem. -->\n*Steps:*\n\n1. Make a map(freq) for storing key and value i.e. nums[i] and frequency pf nums[i].\n```java []\nMap<Integer, Integer> freq = new HashMap<>();\n```\n```C++ []\nunordered_map<int, int> freq;\n```\n2. For Java, you need to convert the int to Integer type for using inbuilt sorting techniques.\n3. Assign key and value to `freq` map.\n\n```java []\nInteger[] newNums = new Integer[nums.length];\n\nfor (int i = 0; i < nums.length; i++) {\n freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1);\n newNums[i] = nums[i];\n}\n```\n```C++ []\nfor (int num : nums) {\n freq[num]++;\n}\n```\n4. Now use inbuilt sorting method to sort according to the question given.\n\n```java []\nArrays.sort(newNums, (n1, n2) -> {\n if (freq.get(n1) != freq.get(n2)) {\n // if freq of numbers are not equal then return in increasing order based on\n // freq.\n return freq.get(n1) - freq.get(n2);\n } else {\n // otherwise sort them in decreasing order based on number in nums.\n return n2 - n1;\n }\n});\n```\n```C++ []\nsort(nums.begin(), nums.end(), [&](int n1, int n2) {\n if (freq[n1] != freq[n2]) {\n // if freq of numbers are not equal then return in increasing\n // order based on freq.\n return freq[n1] < freq[n2];\n } else {\n // otherwise sort them in decreasing order based on number in\n // nums.\n return n2 < n1;\n \n});\n```\n5. Now we have aur sorted nums. For Java we will convert it into `int` and return.\n\n```java []\nfor (int i = 0; i < nums.length; i++) {\n nums[i] = newNums[i];\n}\n\nreturn nums;\n```\n```C++ []\nreturn nums;\n```\n\n\n# Complexity \uD83D\uDC69\u200D\uD83D\uDCBB\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code \uD83D\uDE0A\uD83D\uDCBB\n```java []\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> freq = new HashMap<>();\n Integer[] newNums = new Integer[nums.length];\n\n for (int i = 0; i < nums.length; i++) {\n freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1);\n newNums[i] = nums[i];\n }\n\n Arrays.sort(newNums, (n1, n2) -> {\n if (freq.get(n1) != freq.get(n2)) {\n // if freq of numbers are not equal then return in increasing order based on\n // freq.\n return freq.get(n1) - freq.get(n2);\n } else {\n // otherwise sort them in decreasing order based on number in nums.\n return n2 - n1;\n }\n });\n\n for (int i = 0; i < nums.length; i++) {\n nums[i] = newNums[i];\n }\n\n return nums;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> freq;\n\n for (int num : nums) {\n freq[num]++;\n }\n\n sort(nums.begin(), nums.end(), [&](int n1, int n2) {\n if (freq[n1] != freq[n2]) {\n // if freq of numbers are not equal then return in increasing\n // order based on freq.\n return freq[n1] < freq[n2];\n } else {\n // otherwise sort them in decreasing order based on number in\n // nums.\n return n2 < n1;\n }\n });\n\n return nums;\n }\n};\n```\n\nUpvote\uD83D\uDC4D and comment\u2328\uFE0F.\nPlease let me know if it helped you.\n\nTHANK YOU! \uD83D\uDE0A\n
48
0
['Array', 'Hash Table', 'Sorting', 'C++', 'Java']
8
sort-array-by-increasing-frequency
Java HashMap Collections.sort() easy to understand
java-hashmap-collectionssort-easy-to-und-xcrr
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int num : nums) {\n
coolmike
NORMAL
2021-01-24T18:14:13.488713+00:00
2021-01-24T18:14:13.488744+00:00
8,184
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int num : nums) {\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n \n List<Integer> list = new ArrayList<>(map.keySet());\n Collections.sort(list, (a, b) -> {\n return (map.get(a) == map.get(b))? b - a : map.get(a) - map.get(b);\n });\n \n int[] res = new int[nums.length];\n int i = 0;\n for (int num : list) {\n for (int j = 0; j < map.get(num); j++) {\n res[i++] = num;\n }\n }\n return res;\n }\n}\n```
44
4
['Java']
9
sort-array-by-increasing-frequency
1636. Sort Array by Increasing Frequency Javascript solution
1636-sort-array-by-increasing-frequency-5c50d
\n\nvar frequencySort = function(nums) {\n const map = new Map();\n for (let n of nums) {\n map.set(n, (map.get(n) + 1) || 1);\n }\n return n
kondaldurgam
NORMAL
2020-10-31T16:39:07.751635+00:00
2020-10-31T16:39:07.751670+00:00
3,610
false
```\n\nvar frequencySort = function(nums) {\n const map = new Map();\n for (let n of nums) {\n map.set(n, (map.get(n) + 1) || 1);\n }\n return nums.sort((a, b) => map.get(a) - map.get(b) || b - a)\n};\n```
43
0
['JavaScript']
3
sort-array-by-increasing-frequency
C++/Python3 Sort by Count
cpython3-sort-by-count-by-votrubac-7rrk
C++\nSince the range of numbers is limited, and I am using array to collect count for the performance.\ncpp\nvector<int> frequencySort(vector<int>& nums) {\n
votrubac
NORMAL
2020-10-31T16:00:44.916506+00:00
2020-10-31T17:22:53.899994+00:00
10,054
false
**C++**\nSince the range of numbers is limited, and I am using array to collect count for the performance.\n```cpp\nvector<int> frequencySort(vector<int>& nums) {\n int cnt[201] = {};\n for (auto n : nums)\n ++cnt[n + 100];\n sort(begin(nums), end(nums), [&](int a, int b) {\n return cnt[a + 100] == cnt[b + 100] ? a > b : cnt[a + 100] < cnt[b + 100];\n });\n return nums;\n}\n```\n\n**Python 3**\n```python\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n cnt = collections.Counter(nums)\n return sorted(nums, key = lambda n: (cnt[n], -n))\n```
43
6
[]
7
sort-array-by-increasing-frequency
JAVA | HashMap | Sorting | Explained
java-hashmap-sorting-explained-by-sourin-xgd1
Please Upvote :D\n---\n- We create a frequency map as well as an arraylist to store the values in nums so that we can custom sort it.\n\n- We then sort the lis
sourin_bruh
NORMAL
2022-09-25T12:13:56.617751+00:00
2023-01-07T07:17:35.464999+00:00
10,254
false
# Please Upvote :D\n---\n- We create a frequency map as well as an arraylist to store the values in nums so that we can custom sort it.\n\n- We then sort the list in increasing order of map values (i.e. the frequency of nums elements).\n\n- If two or more values (frequencies) happens to be same, then we sort the elements itself in decreasing order. (Look at the example testcases for a better understanding).\n\n- We return the list by convertng it to an array.\n``` java []\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n List<Integer> ans = new ArrayList<>();\n for (int n : nums) { \n ans.add(n);\n map.put(n, map.getOrDefault(n, 0) + 1);\n }\n\n Collections.sort(ans, (a, b) -> \n (map.get(a) == map.get(b))? b - a : map.get(a) - map.get(b)\n );\n\n return ans.stream().mapToInt(i -> i).toArray(); // O(n)\n }\n}\n\n// TC: O(n) + O(n * logn) + O(n) => O(n * logn)\n// SC: O(n)\n```
39
0
['Hash Table', 'Sorting', 'Java']
8
sort-array-by-increasing-frequency
Easy Python Solution with Explanation
easy-python-solution-with-explanation-by-2sjl
\tfrom collections import Counter\n\tclass Solution:\n\t\tdef frequencySort(self, nums: List[int]) -> List[int]:\n\t\t\td = Counter(nums)\n\t\t\tdef check(x):\n
shadow_sm36
NORMAL
2020-11-01T07:42:57.495338+00:00
2020-11-01T07:51:26.888058+00:00
5,756
false
\tfrom collections import Counter\n\tclass Solution:\n\t\tdef frequencySort(self, nums: List[int]) -> List[int]:\n\t\t\td = Counter(nums)\n\t\t\tdef check(x):\n\t\t\t\treturn d[x]\n\n\t\t\tnums.sort(reverse=True)\n\t\t\tnums.sort(key=check)\n\t\t\treturn nums\n\t\t\t\nSo the basic idea is we use the Python\'s inbuilt sort function with a custom method which returns the frequency of that element in the array to sort. So, first we create a frequency array using the Python\'s Counter function *(This returns a dictionary, the same could have been manually using a blank dictionary but since we can utilise the capabilities of Python, that is what we do here.)* \n\nand we create a new function which returns the frequency of that element in our array *(The same could have been done easier with a lambda function as well, but this was my first instinct so I went with this)*\n\nNow, we reversed sorted the list first normally so that when sorting the second time using our custom sort, our answer comes out to be what we want, *(decreasing order for elements with the same frequency)* \n\nNext we use our custom sort function which generates a frequency wise + decreasing order for same frequency elements. Our inbuilt custom sort is stable, meaning it won\'t change the relative order among elements. \n\nExample:\n\tIn Stable Frequency Wise Sort:\n\t`[1,3,3,2,4] --> [1,2,4,3,3] (relative order of 1,2,4 is maintained)`\n\tIn Unstable Frequency Wise Sort:\n\t`[1,3,3,2,4] --> [4,1,2,3,3] (relative order of 1,2,4 is not maintained)`\n\t\n\n**Note:** We can achieve this in one sort also by instead of returning a single key in our *check* function, we return a tuple of keys. \n\nSo that would make our *check* function something like: \n\n```\ndef check(x):\n\treturn (d[x], -x)\n```\nThe purpose of *-x* is because in case of elements with the same frequency, we want them sorted in reverse sorted order.\n\nExample: `nums = [1,2,3,4]`\n\nSo, for this list, the element:\n* 1 --> (1, -1)\n* 2 --> (1, -2)\n* 3 --> (1, -3)\n* 4 --> (1, -4)\n* element --> (frequency of element, -element)\n\nSo, first our list is sorted based on the first element, so since all are 1. Nothing happens. Next, we sort all the 1s based on the second element. So, -4 is the smallest so, that comes first, then -3 then -2 and lastly -1.\n\nSo the order becomes: (1, -4) , (1, -3), (1, -2), (1, -1) which means [4,3,2,1]. Which is what we wanted. \n\nPlease feel free to ask anything here, I will be happy to help/respond.
36
2
['Sorting', 'Python', 'Python3']
5
sort-array-by-increasing-frequency
C++| 100% faster| EASY TO UNDERSTAND | fast and efficient code using comparator function
c-100-faster-easy-to-understand-fast-and-33f9
Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome\n```\nclass
aarindey
NORMAL
2021-06-17T20:19:07.565333+00:00
2021-06-17T20:19:07.565365+00:00
3,984
false
***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome***\n```\nclass Solution {\npublic:\n bool static comp(pair<int,int> a,pair<int,int> b)\n {\n if(a.second==b.second)\n return a>b; \n else\n return a.second<b.second;\n }\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> mp;\n for(int i=0;i<nums.size();i++)\n {\n mp[nums[i]]++;\n }\n vector<pair<int,int> > vec;\n for(auto pr:mp)\n {\n vec.push_back(pr);\n }\n sort(vec.begin(),vec.end(),comp);\n \n vector<int> ans;\n for(int i=0;i<vec.size();i++)\n {\n while(vec[i].second>0)\n {\n ans.push_back(vec[i].first);\n vec[i].second--;\n }\n }\n return ans;\n }\n};
35
2
['C']
3
sort-array-by-increasing-frequency
[java/Python 3] Sort frequency followed by value.
javapython-3-sort-frequency-followed-by-n69hh
\njava\n public int[] frequencySort(int[] nums) {\n var freq = new HashMap<Integer, Integer>();\n for (int n : nums) {\n freq.put(n,
rock
NORMAL
2020-10-31T16:31:10.346370+00:00
2020-11-22T17:44:26.289102+00:00
5,442
false
\n```java\n public int[] frequencySort(int[] nums) {\n var freq = new HashMap<Integer, Integer>();\n for (int n : nums) {\n freq.put(n, 1 + freq.getOrDefault(n, 0));\n }\n var pq = new PriorityQueue<Integer>(Comparator.<Integer, Integer>comparing(i -> freq.get(i)).thenComparing(i -> -i));\n for (int n : nums) {\n pq.offer(n);\n }\n int[] ans = new int[nums.length];\n for (int i = 0; !pq.isEmpty(); ++i) {\n ans[i]= pq.poll();\n }\n return ans;\n }\n```\n```python\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq = Counter(nums)\n return sorted(nums, key=lambda x : (freq[x], -x))\n```
28
2
[]
11
sort-array-by-increasing-frequency
Python 1-liner
python-1-liner-by-lokeshsk1-34mk
\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sorted(sorted(nums,reverse=1),key=nums.count)\n
lokeshsk1
NORMAL
2020-12-07T12:33:51.755506+00:00
2020-12-07T12:34:04.970476+00:00
2,627
false
```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sorted(sorted(nums,reverse=1),key=nums.count)\n```
26
2
['Python', 'Python3']
9
sort-array-by-increasing-frequency
Simple C++ Solution
simple-c-solution-by-arbind007-hmuq
\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map <int,int> mp;\n priority_queue <pair <int,int>> q;
Arbind007
NORMAL
2022-02-02T07:40:28.181622+00:00
2022-10-09T06:19:07.762082+00:00
5,661
false
```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map <int,int> mp;\n priority_queue <pair <int,int>> q;\n for(int i=0;i<nums.size();i++){\n mp[nums[i]]++;\n }\n for(auto &i:mp){\n q.push({-i.second,i.first});\n }\n nums.clear();\n while(!q.empty()){\n for(int i=0;i<-(q.top().first);i++){\n nums.push_back(q.top().second);\n }\n q.pop();\n }\n return nums;\n }\n};\n```
24
0
['Array', 'Hash Table', 'Sorting', 'Heap (Priority Queue)', 'C++']
2
sort-array-by-increasing-frequency
[c++] || Sort Array by Increasing Frequency
c-sort-array-by-increasing-frequency-by-m6dyr
\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n map<int,int> mp;\n for(int i=0;i<nums.size();i++){\n
durgirajesh_
NORMAL
2021-09-20T05:47:09.411899+00:00
2021-09-20T05:47:09.411949+00:00
3,275
false
```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n map<int,int> mp;\n for(int i=0;i<nums.size();i++){\n mp[nums[i]]++;\n }\n priority_queue<pair<int,int>> pq;\n for(auto it : mp){\n pq.push({-it.second,it.first});\n }\n vector<int> result;\n while(!pq.empty()){\n int x = pq.top().first;\n for(int i=0;i<abs(x);i++){\n result.push_back(pq.top().second);\n }\n pq.pop();\n }\n return result;\n }\n};\n```
24
0
['C', 'Heap (Priority Queue)']
4
sort-array-by-increasing-frequency
Simple Python solution with explanation
simple-python-solution-with-explanation-gwu28
We are going to use a dictionary to keep track of the frequeny that a number appears in the array. After we have done that we first sort the array in decreasing
stevenbooke
NORMAL
2021-02-21T01:11:35.394801+00:00
2021-02-21T01:11:35.394827+00:00
2,013
false
We are going to use a dictionary to keep track of the frequeny that a number appears in the array. After we have done that we first sort the array in decreasing order and then sort it in increasing order by frequency. This works because sorts are guarenteed to be stable. Read this if you need help understanding why this works. https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts \n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n d = {}\n for num in nums:\n if num not in d:\n d[num] = 1\n else:\n d[num] += 1\n return sorted(sorted(nums, reverse=True), key=lambda x: d[x])\n```
20
2
['Python']
3
sort-array-by-increasing-frequency
Easiest one line solution in python
easiest-one-line-solution-in-python-by-m-ttii
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Mohammad_tanveer
NORMAL
2023-03-04T20:05:12.251357+00:00
2023-03-04T20:05:12.251391+00:00
1,657
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sorted(sorted(nums,reverse=1),key=nums.count)\n\n #please do upvote it will encourage me alot\n\t\t\n\t\t\n \n```
17
0
['Python3']
0
sort-array-by-increasing-frequency
✅Easiest 3 Step Cpp / Java / Py / JS Solution | Two Approaches 🏆| Map+Heap
easiest-3-step-cpp-java-py-js-solution-t-ohnn
Explanation Heap\n##### Step 1: Count Frequencies\nWe use an unordered map freq_map to count the frequency of each number.\n##### Step 2:Heap (Priority Queue):\
dev_yash_
NORMAL
2024-07-23T01:50:09.860454+00:00
2024-07-23T01:50:09.860488+00:00
4,017
false
### **Explanation Heap**\n##### **Step 1: Count Frequencies**\nWe use an unordered map freq_map to count the frequency of each number.\n##### **Step 2:Heap (Priority Queue):**\n* We use a max-heap (priority queue) to store the numbers in such a way that they are ordered by their frequency and value.\n* The custom comparator ensures that:\n* If two numbers have the same frequency, they are ordered by their value in decreasing order.\n* Otherwise, they are ordered by their frequency in increasing order\n\n##### **Step 3: Extracting from Heap:l**\nBy repeatedly removing the top element from the heap, we reconstruct the sorted array.\n\n### C++\n```\n\n//Map\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> freq_map;\n // Count the frequency of each number\n for (int num : nums) {\n freq_map[num]++;\n }\n \n // Sort based on frequency and value\n sort(nums.begin(), nums.end(), [&freq_map](int a, int b) {\n // If frequencies are different, sort by frequency\n if (freq_map[a] != freq_map[b]) {\n return freq_map[a] < freq_map[b];\n }\n // If frequencies are the same, sort by value in decreasing order\n return a > b;\n });\n \n return nums;\n }\n};\n```\n```\n//heap\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> freq_map;\n \n // Step 1: Count the frequency of each number\n for (int num : nums) {\n freq_map[num]++;\n }\n \n // Step 2: Use a max-heap to sort by frequency and value\n // Define a custom comparator for the priority queue\n auto comparator = [&freq_map](int a, int b) {\n if (freq_map[a] == freq_map[b]) {\n return a < b; // For the same frequency, sort by value in decreasing order\n }\n return freq_map[a] > freq_map[b]; // Sort by frequency in increasing order\n };\n \n priority_queue<int, vector<int>, decltype(comparator)> max_heap(comparator);\n \n // Add all numbers to the heap\n for (int num : nums) {\n max_heap.push(num);\n }\n \n // Step 3: Extract from the heap to get the sorted array\n vector<int> result;\n while (!max_heap.empty()) {\n result.push_back(max_heap.top());\n max_heap.pop();\n }\n \n return result;\n }\n};\n\n\n```\n### Java\n```\n\n//Unordered Map\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> freqMap = new HashMap<>();\n \n // Count the frequency of each number\n for (int num : nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n \n // Convert the array to Integer list for sorting\n Integer[] numsArray = Arrays.stream(nums).boxed().toArray(Integer[]::new);\n \n // Sort based on frequency and value\n Arrays.sort(numsArray, (a, b) -> {\n if (!freqMap.get(a).equals(freqMap.get(b))) {\n return freqMap.get(a) - freqMap.get(b); // Sort by frequency\n } else {\n return b - a; // Sort by value in decreasing order\n }\n });\n \n // Convert back to int array\n return Arrays.stream(numsArray).mapToInt(Integer::intValue).toArray();\n }\n}\n\n```\n```\n//Hashing\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> freqMap = new HashMap<>();\n \n // Count the frequency of each number\n for (int num : nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n \n // Use a priority queue (min-heap) to sort by frequency and value\n PriorityQueue<Integer> heap = new PriorityQueue<>(\n (a, b) -> freqMap.get(a).equals(freqMap.get(b)) ? b - a : freqMap.get(a) - freqMap.get(b)\n );\n \n // Add all numbers to the heap\n for (int num : nums) {\n heap.add(num);\n }\n \n // Extract from heap to get the sorted array\n int[] result = new int[nums.length];\n int index = 0;\n while (!heap.isEmpty()) {\n result[index++] = heap.poll();\n }\n \n return result;\n }\n}\n\n```\n\n### Python3\n```\n\n#Map\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq_map = Counter(nums)\n \n # Sort based on frequency and value\n nums.sort(key=lambda x: (freq_map[x], -x))\n \n return nums\n \n \n ```\n ```\n#Heap\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq_map = Counter(nums)\n \n # Use a heap to sort by frequency and value\n heap = []\n for num in nums:\n heapq.heappush(heap, (freq_map[num], -num))\n \n result = []\n while heap:\n result.append(heapq.heappop(heap)[1] * -1)\n \n return result\n\n```\n### JavaScript\n```\n\n//Map\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar frequencySort = function(nums) {\n const freqMap = new Map();\n \n // Count the frequency of each number\n nums.forEach(num => {\n freqMap.set(num, (freqMap.get(num) || 0) + 1);\n });\n \n // Sort based on frequency and value\n nums.sort((a, b) => {\n const freqA = freqMap.get(a);\n const freqB = freqMap.get(b);\n if (freqA !== freqB) {\n return freqA - freqB; // Sort by frequency\n } else {\n return b - a; // Sort by value in decreasing order\n }\n });\n \n return nums;\n};\n```\n```\n\n//Heap\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar frequencySort = function(nums) {\n const freqMap = new Map();\n \n // Count the frequency of each number\n nums.forEach(num => {\n freqMap.set(num, (freqMap.get(num) || 0) + 1);\n });\n \n // Create a min-heap using a priority queue\n const heap = new MinPriorityQueue({ \n compare: (a, b) => {\n if (freqMap.get(a) !== freqMap.get(b)) {\n return freqMap.get(a) - freqMap.get(b);\n } else {\n return b - a;\n }\n }\n });\n \n // Add all numbers to the heap\n nums.forEach(num => heap.enqueue(num));\n \n // Extract from heap to get the sorted array\n const result = [];\n while (!heap.isEmpty()) {\n result.push(heap.dequeue());\n }\n \n return result;\n};\n\n\n```\n#### STAY COOL STAY DISCIPLINED..\n\n![image](https://assets.leetcode.com/users/images/ad294515-01e3-4704-a668-9bcc5b0e822c_1717851160.1975598.gif)
16
0
['Array', 'Hash Table', 'C', 'Sorting', 'Heap (Priority Queue)', 'Python', 'Python3', 'JavaScript']
6
sort-array-by-increasing-frequency
EASY C++ SOLUTION | HEAPS | MAPS
easy-c-solution-heaps-maps-by-theadeshkh-5czb
\nvector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> m;\n unordered_map<int, int>::iterator it;\n priority_queue<pair
theadeshkhanna
NORMAL
2022-05-08T19:40:52.233051+00:00
2022-05-08T19:40:52.233081+00:00
2,829
false
```\nvector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> m;\n unordered_map<int, int>::iterator it;\n priority_queue<pair<int, int>> pq;\n \n vector<int> v;\n int n = nums.size();\n \n for (int i = 0; i < n; i++) {\n m[nums[i]]++;\n }\n \n for (it = m.begin(); it != m.end(); it++) {\n pq.push({-1 * it->second, it->first});\n }\n \n while(pq.size() > 0) {\n int freq = -1 * pq.top().first;\n int elem = pq.top().second;\n \n for (int i = 0; i < freq; i++) v.push_back(elem);\n pq.pop();\n }\n \n return v;\n }\n```
14
0
['C', 'Heap (Priority Queue)', 'C++']
3
sort-array-by-increasing-frequency
Python one line solution
python-one-line-solution-by-tovam-rdcs
Python :\n\n\ndef frequencySort(self, nums: List[int]) -> List[int]:\n\treturn sorted(sorted(nums, reverse=True), key=nums.count)\n\n\nLike it ? please upvote !
TovAm
NORMAL
2021-10-25T21:21:08.655222+00:00
2021-10-25T21:21:08.655252+00:00
1,321
false
**Python :**\n\n```\ndef frequencySort(self, nums: List[int]) -> List[int]:\n\treturn sorted(sorted(nums, reverse=True), key=nums.count)\n```\n\n**Like it ? please upvote !**
14
1
['Python', 'Python3']
1
sort-array-by-increasing-frequency
Easy to Understand Python Solution
easy-to-understand-python-solution-by-ay-ll69
\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n\n res = sorted(nums, key=nums.count)\n
ayushi7rawat
NORMAL
2021-05-06T04:31:39.766692+00:00
2021-05-06T04:31:39.766733+00:00
1,201
false
```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n\n res = sorted(nums, key=nums.count)\n return res\n```
14
2
['Python']
2
sort-array-by-increasing-frequency
C++ || Hashmap || Simple + Optimized
c-hashmap-simple-optimized-by-meurudesu-vchr
\n# Code\n\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> mp;\n for(auto i : nums) { //
meurudesu
NORMAL
2024-02-07T10:56:49.885634+00:00
2024-02-07T10:56:49.885667+00:00
1,698
false
\n# Code\n```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> mp;\n for(auto i : nums) { // store cnt of every num\n mp[i]++;\n }\n sort(nums.begin(), nums.end(), [&](int a, int b) {\n if(mp[a] == mp[b]) return a > b; // \u2193\n else return mp[a] < mp[b]; // \u2191\n });\n return nums; \n }\n};\n```
13
0
['Hash Table', 'C++']
4
sort-array-by-increasing-frequency
Java Easy to understand using Comparator class
java-easy-to-understand-using-comparator-xew3
\nclass Solution {\n HashMap<Integer, Integer> map = new HashMap<>();\n \n class Sorter implements Comparator<Integer>{\n\t//comparing the frequencies
harshu175
NORMAL
2021-04-23T21:14:08.218211+00:00
2021-04-23T21:14:08.218255+00:00
2,149
false
```\nclass Solution {\n HashMap<Integer, Integer> map = new HashMap<>();\n \n class Sorter implements Comparator<Integer>{\n\t//comparing the frequencies \n public int compare(Integer a, Integer b){\n if(map.get(a) == map.get(b)){\n return b-a;\n }else{\n return map.get(a) - map.get(b);\n }\n }\n }\n public int[] frequencySort(int[] nums) {\n\t//using arraylist beacuse of collection\n\t\n ArrayList<Integer> list = new ArrayList<>();\n for(int i=0; i<nums.length; i++){\n list.add(nums[i]);\n map.put(nums[i], map.getOrDefault(nums[i], 0) +1);\n }\n //modifying the inbuilt collection.sort to use our sorter class\n Collections.sort(list , new Sorter());\n \n for(int i=0; i<list.size(); i++){\n nums[i] = list.get(i);\n }\n return nums;\n }\n}\n```
13
1
['Array', 'Java']
1
sort-array-by-increasing-frequency
C++ Sort by frequency
c-sort-by-frequency-by-lzl124631x-7ytw
See my latest update in repo LeetCode\n\n## Solution 1. Sort\n\ncpp\n// OJ: https://leetcode.com/contest/biweekly-contest-38/problems/sort-array-by-increasing-f
lzl124631x
NORMAL
2020-10-31T16:02:48.992134+00:00
2020-11-01T20:11:03.307707+00:00
2,896
false
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Sort\n\n```cpp\n// OJ: https://leetcode.com/contest/biweekly-contest-38/problems/sort-array-by-increasing-frequency/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(N)\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& A) {\n unordered_map<int, int> cnt;\n for (int n : A) cnt[n]++;\n sort(begin(A), end(A), [&](int a, int b) { return cnt[a] != cnt[b] ? cnt[a] < cnt[b] : a > b; });\n return A;\n }\n};\n```
13
1
[]
4
sort-array-by-increasing-frequency
Java Easy Solution || Sort Method
java-easy-solution-sort-method-by-aanand-xx4h
```\npublic int[] frequencySort(int[] nums) {\n Map map=new HashMap<>();//map to store count of each number\n List list=new ArrayList<>();\n
aanandsj1706
NORMAL
2020-10-31T16:02:09.924780+00:00
2020-10-31T16:06:42.982881+00:00
3,604
false
```\npublic int[] frequencySort(int[] nums) {\n Map<Integer,Integer> map=new HashMap<>();//map to store count of each number\n List<Integer> list=new ArrayList<>();\n for(int num:nums){\n if(map.containsKey(num))\n map.put(num,map.get(num)+1);\n else{\n list.add(num);\n map.put(num,1);\n }\n }\n Collections.sort(list,(a,b)->map.get(a)==map.get(b)?(b-a):map.get(a)-map.get(b));//sorting based on count value first and then number value\n int arr[]=new int[nums.length];\n int k=0;\n for(int num:list){\n int cnt=map.get(num);\n while(cnt>0){\n arr[k++]=num;\n cnt--;\n }\n }\n return arr;\n }
13
1
[]
6
sort-array-by-increasing-frequency
Javascript sort
javascript-sort-by-fbecker11-59dn
\nvar frequencySort = function(nums) {\n const map = new Map()\n for(let n of nums){\n map.set(n, (map.get(n) || 0)+1)\n }\n return nums.sort((a,b)=>{\n
fbecker11
NORMAL
2020-11-25T14:47:48.460247+00:00
2020-11-25T14:47:48.460277+00:00
1,714
false
```\nvar frequencySort = function(nums) {\n const map = new Map()\n for(let n of nums){\n map.set(n, (map.get(n) || 0)+1)\n }\n return nums.sort((a,b)=>{\n if(map.get(a) === map.get(b)){\n return b-a\n }else{\n return map.get(a) - map.get(b)\n }\n })\n};\n```
12
0
['Sorting', 'JavaScript']
3
sort-array-by-increasing-frequency
Sort Array by Increasing Frequency [ C++] 96% faster solution
sort-array-by-increasing-frequency-c-96-zj5ek
Intuition\n Describe your first thoughts on how to solve this problem. \nFirsly as we see frequecy the intuition is to use map. We store the freq in map and the
shreyajain1808
NORMAL
2023-06-01T18:01:24.593120+00:00
2023-06-01T18:01:24.593159+00:00
2,296
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirsly as we see frequecy the intuition is to use map. We store the freq in map and then think of how to use heap for sorting.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMap stores te frequency of each element so we iterate through the map and push into the min heap the elements one by one based on frequency but there is a catch where two elements have same frequency they need to be arranged in descending order so we need a special comparator to perform this operation on heap.\nSo we make use of \nbool operator()(pair<int,int> a,pair<int,int> b)\n{\n if(a.first==b.first)\n {\n a.second < b.second;\n }\n return a.first > b.first;\n}\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```\nclass MyComp\n{\n public:\n bool operator()(pair<int,int> a,pair<int,int> b)\n {\n if(a.first==b.first)\n {\n return a.second < b.second;\n }\n return a.first > b.first;\n\n }\n};\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n map<int,int> m;\n priority_queue<pair<int,int>,vector<pair<int,int>>,MyComp>pq;\n vector<int> ans;\n for(int i=0;i<nums.size();i++)\n {\n m[nums[i]]++;\n }\n for(auto it=m.begin();it!=m.end();it++)\n {\n pq.push({it->second,it->first});\n }\n while(!pq.empty())\n {\n int freq=pq.top().first;\n int el=pq.top().second;\n pq.pop();\n for(int i=0;i<freq;i++)\n {\n ans.push_back(el);\n }\n }\n return ans;\n }\n};\n```
11
1
['C++']
0
sort-array-by-increasing-frequency
Java SIMPLE solution using TreeMap and with explanation faster than 100.00%
java-simple-solution-using-treemap-and-w-zgxx
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n int[] bucket = new int[201]; //An array bucket to store frequency of numbers ranged be
sandip_chanda
NORMAL
2020-10-31T17:40:22.012854+00:00
2020-10-31T18:13:20.359751+00:00
2,403
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n int[] bucket = new int[201]; //An array bucket to store frequency of numbers ranged between -100 to 100\n for(int num : nums) {\n bucket[num+100]++;\n }\n TreeMap<Integer, List<Integer>> map = new TreeMap(); //TreeMap to store numbers list by their frequency and in case of same frequency the list will be in descending order\n for(int i=200; i>=0; i--) {\n if(bucket[i] > 0) {\n if(!map.containsKey(bucket[i]))\n map.put(bucket[i], new ArrayList<Integer>());\n List<Integer> temp = map.get(bucket[i]);\n temp.add(i-100);\n map.put(bucket[i], temp);\n }\n }\n int[] result = new int[nums.length];\n int index = 0;\n for(Map.Entry<Integer, List<Integer>> entry : map.entrySet()) { //Finally generate the result array\n int freq = entry.getKey();\n for(int num : entry.getValue())\n for(int i=0; i<freq; i++)\n result[index++] = num;\n }\n return result;\n }\n}\n```
11
0
['Java']
2
sort-array-by-increasing-frequency
Very Easy approach | Simple map + sorting | Vid explantion
very-easy-approach-simple-map-sorting-vi-q6db
Vid Explanation\nhttps://youtu.be/Ys7eYFNzgEI\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe natural intuition for this problem
Atharav_s
NORMAL
2024-07-23T01:55:23.624670+00:00
2024-07-23T01:55:23.624687+00:00
3,243
false
# Vid Explanation\nhttps://youtu.be/Ys7eYFNzgEI\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe natural intuition for this problem is to first count the occurrences of each number in the array. This gives us a mapping between numbers and their frequencies. Then, we can sort the numbers based on their frequencies. However, for numbers with the same frequency, we need to sort them in descending order.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Count Frequencies: We use an unordered_map to store the frequency of each number. We iterate through the nums array and increment the count for each number encountered.\n2. Group by Frequency: We create a map where the key is the frequency and the value is a vector of numbers with that frequency. This groups numbers based on how many times they appear in the array.\n3. Sort within Frequency Groups: For each frequency group (key-value pair in the freqGrp map), we check if the size of the value vector (number of elements with that frequency) is greater than 1. If so, we sort the vector in descending order using sort(it.second.rbegin(), it.second.rend()). This ensures numbers with the same frequency appear in the output sorted by their value (larger values first).\n4. Build the Result: We iterate through the freqGrp map again. For each key-value pair:\nIf there are multiple elements with the same frequency (vector size > 1), iterate through the vector and append the number to the result vector ans the number of times equal to its frequency.\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n\n unordered_map<int,int> freq;\n\n for(auto &num: nums){\n\n freq[num]++;\n \n }\n\n map<int,vector<int>> freqGrp;\n\n for(auto &it: freq){\n\n freqGrp[it.second].push_back(it.first);\n \n }\n\n vector<int> ans;\n\n for(auto &it: freqGrp){\n\n if(it.second.size() > 1){\n\n sort(it.second.rbegin(), it.second.rend());\n \n }\n\n for(auto &num: it.second){\n\n for(int i=0;i<it.first;i++){\n\n ans.push_back(num);\n \n }\n \n }\n \n }\n\n return ans;\n \n \n }\n};\n```
10
0
['C++']
0
sort-array-by-increasing-frequency
Java || Easy Approach with Explanation || HashMap || Heap( min + max )
java-easy-approach-with-explanation-hash-k5ib
\nclass Solution \n{//T-> O( N log N ) S->O( N )\n public int[] frequencySort(int[] nums)\n {\n Map<Integer, Integer> map= new HashMap<>();//data -
swapnilGhosh
NORMAL
2021-08-03T09:30:19.006868+00:00
2021-08-03T09:37:28.470607+00:00
1,836
false
```\nclass Solution \n{//T-> O( N log N ) S->O( N )\n public int[] frequencySort(int[] nums)\n {\n Map<Integer, Integer> map= new HashMap<>();//data -- frequency\n \n for(int data: nums)//calculating and putting the frequency of data \n map.put(data, map.getOrDefault(data, 0)+1);\n \n PriorityQueue<Map.Entry<Integer, Integer>> heap= new PriorityQueue<>((a, b)->{\n return (a.getValue() == b.getValue())? b.getKey() - a.getKey() : a.getValue() - b.getValue();//maxHeap(data) (when frequency are same)//false impression tro priority Queue || minHeap(frequency)\n });\n \n for(Map.Entry<Integer, Integer> entry: map.entrySet())//putting all the Entry into the heap \n heap.offer(entry);\n \n int index= 0;//index is for insering into the same array\n \n while(heap.size() != 0)//doing the operation till the heapis Empty\n {\n Map.Entry<Integer, Integer> temp= heap.poll();//getting the min frequency Entry\n \n int val= temp.getKey();//extracting the data from the Entry\n int freq= temp.getValue();//extracting the frequency of the data from the Entry\n \n for(int i= 0; i< freq; i++)//overwridding the values into the Array, to reduce the space \n nums[index+i]= val;//adding the value \n index+= freq;//index position maintaining \n }\n \n return nums;//returning the resultant array \n }\n}//please do Upvote, it helps a lot\n```
10
0
['Heap (Priority Queue)', 'Java']
0
sort-array-by-increasing-frequency
Just Counting | C++ In-Place Sorting 0 ms 100% | Python3 One-Liners 38 ms 98%
just-counting-c-in-place-sorting-0-ms-10-og09
Intuition\nThe task is to sort the input array by the element frequencies, ascending. Two elements with the same frequencies should be arranged in descending or
sergei99
NORMAL
2024-07-23T09:28:59.473545+00:00
2024-10-22T01:12:32.288260+00:00
2,963
false
# Intuition\nThe task is to sort the input array by the element frequencies, ascending. Two elements with the same frequencies should be arranged in descending order by their value. There could be up to $100$ elements in the range $[-100, 100]$.\n\n# Approach\n\n## C++\n\nFor fast enough languages we just introduce an array of frequency+value pairs. Since both count and value fit an 8-bit quantity, we allocate 16 bit for the pair, and the array size would be 201. The frequency would occupy a high-order byte, and the value would be in the low-order byte. To ensure proper comparison, we store frequencies as a complement to 100, so that 0 becomes 100, 1 becomes 99, etc., and the max possible frequency of 100 becomes 0. The value part is biased by 100, so that -100 becomes 0, -99 becomes 1, etc., and 100 becomes 200. This ensures the proper comparison ordering.\n\nWhen initializing the frequencies, we put 100 in the high-order byte, and the array index (0..200) in the low-order byte. This is easily achievable with `iota` in C++.\n\nThen we run through the array elements and for each element we subtract 1 from the frequency byte, i.e. we subtract 256 from the array element.\n\nThen we sort the array in descending order, which ensures that it\'s ascending by frequency and descending by value, and frequency comes first in comparisons. It\'s small enough to use a conventional STL sort (though it\'s still possible to apply a count sorting to it).\n\nFinally, we unfold the counters to the input array to reuse its storage. Each value (low-order byte) is added its frequency times (high order byte complemented to 100 again).\n\n## Java\n\nA Java solution is similar to a C++ one with the exception that we store frequencies as is and complement values. The point is that `Arrays.sort` can only sort ascending, and boxing and comparators would kill performance. Since there are no on-stack allocation of arrays in Java, we also use a static link to the frequencies array, allocated once and for all.\n\n## Python\n\nFor Python it\'s somewhat a different story. When programming in Python we should stick to libraries (written mostly in C) and use the minimum of Python code and data.\n\nThe counting could be achieved by accumulating values in `statistics.Counter` which is essentially a dictionary with values as keys and their frequencies as values.\n\nThe `Counter` can return accumulated statistics as key-value pairs, either sorted by counter descending (using `most_common`) or in a random order like `dict` does (using `items`). Elements with same frequencies would be returned by `most_common` in their order of appearence in the input data, which is not what we want. We have to apply our own ordering, therefore we use `Counter.items` method to avoid extra sorting overhead.\n\nOnce we have a sequence of pairs, we could sort it by count ascending and value descending, passing an appopriate sort key to the method.\n\nAnd finally we need to unfold the `Counter` to an array as per task requirements. We use two approaches here: `sum` of lists and chaining of iterators, just to compare their execution statistics. `sum` and list multiplication are builtin capabilities of the language, and `repeat` and `chain` are available in the `itertools` library.\n\nWhen we use `sum` to concatenate the lists, we have to materialize a list for each value, then a list for value its count times, a list of lists and a list for each intermediate concatenation (so if we have e.g. lists a, b, c, d, then intermediate lists are created for `a`, `b`, `c`, `d`, their multiples by count, then a list of lists (containing all multiples), then `a + b`, `a + b + c` and a final one for `a + b + c + d`).\n\nThe itertools stuff has an advantage that it operates iterators. `repeat` creates an iterator to return the given value the given number of times, and `chain` flattens the iterator of iterators to an iterator of values. Technically we would need to wrap the chain in a `list` afterwards, but the function happens to pass tests without that.\n\n# Complexity\n- Time complexity: $O(n \\times r \\times log(r))$\n\n- Space complexity: $O(r)$ ($O(n + r)$ for Python)\n\n(where $n$ is the input array size, and $r$ is the range of values (i.e. $201$))\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n static vector<int> frequencySort(vector<int>& nums) {\n constexpr int8_t MINV = -100, MAXV = 100;\n constexpr uint8_t FSIZE = MAXV - MINV + 1u;\n uint16_t freqsv[FSIZE];\n iota(freqsv, freqsv + FSIZE, 100u << 8);\n for (const int v : nums)\n freqsv[v-MINV] -= 1u << 8;\n sort(freqsv, freqsv + FSIZE, greater());\n nums.clear();\n for (const uint16_t fv : freqsv)\n nums.insert(nums.end(), 100u - (fv >> 8), (fv & 0xFF) + MINV);\n return move(nums);\n }\n};\n```\n``` Java []\nclass Solution {\n private static final byte MINV = -100, MAXV = 100;\n private static final short FSIZE = MAXV - MINV + 1;\n private static final short[] freqsv = new short[FSIZE];\n \n public static int[] frequencySort(final int[] nums) {\n for (int i = 0; i < FSIZE; i++)\n freqsv[i] = (short)(FSIZE - i);\n for (final int v : nums)\n freqsv[v-MINV] += 1 << 8;\n Arrays.sort(freqsv);\n int i = 0;\n final int VCOMP = FSIZE - MAXV;\n for (final short fv : freqsv)\n Arrays.fill(nums, i, i += (fv >> 8), VCOMP - (fv & 0xFF));\n return nums;\n }\n}\n```\n``` Python3/sum []\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sum([[n] * c for n, c in sorted(Counter(nums).items(), key=lambda p: (p[1], -p[0]))], [])\n```\n``` Python3/chain []\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return chain.from_iterable(repeat(n, c) for n, c in sorted(Counter(nums).items(), key=lambda p: (p[1], -p[0])))\n```\n\n# Measurements\n\n|Language|Time,ms|Beating|Memory,Mb|Beating|Submission Link|\n|-|-|-|-|-|-|\n| C++ | 0 | 100% | 14.92 | 37.05% | https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330318847 |\n| Java | 3 | 97.80% | 43.42 | 98.20% | https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330520862 |\n| Python3/sum | 54 | 30.03% | 16.71 | 12.04% | https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330380423 |\n| Python3/chain | 38 | 98.24% | 16.76 | 12.04% | https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330427477 |\n\nNote that the chaining approach in Python is noticeably faster even with such tiny amount of data.\n
9
0
['Array', 'Bit Manipulation', 'Sorting', 'Counting', 'C++', 'Java', 'Python3']
1
sort-array-by-increasing-frequency
Python 3 || 3 lines, Counter, sort, chain || T/S: 87% / 77%
python-3-3-lines-counter-sort-chain-ts-8-biji
\nLet\'s use an example trace to explain the code.\n\nSuppose that nums = [1,2,1,3,2,3,2].\n\n1. First line trace:\n\nctr = Counter([1,2,1,3,2,3,2]).items()\n
Spaulding_
NORMAL
2024-07-23T00:52:57.018434+00:00
2024-07-25T16:44:25.575503+00:00
721
false
\nLet\'s use an example trace to explain the code.\n\nSuppose that `nums = [1,2,1,3,2,3,2]`.\n\n1. *First line trace*:\n```\nctr = Counter([1,2,1,3,2,3,2]).items()\n = [(1,2), (2,3), (3,2)]\n```\n2. *Second line trace*:\n```\narr = sorted([(1,2), (2,3), (3,2)], key = lambda x: (x[1], -x[0]))\n = [(3,2), (1,2), (2,3)]\n```\n3. *Third line trace*:\n```\n return chain(*[[digit]* cnt for digit,cnt in [(3,2), (1,2), (2,3)]]) \n --> return chain(* [[3]*2, [1]*2, [2]*3])\n --> return chain(* [[3,3], [1,1], [2,2,2]])\n --> return chain( [3,3], [1,1], [2,2,2])\n --> return [3,3, 1,1, 2,2,2]\n```\n_____\nHere\'s the code:\n```\nclass Solution:\n def frequencySort(self, nums: list[int]) -> list[int]:\n\n ctr = Counter(nums).items() # <-- 1)\n\n arr = sorted(ctr, key = lambda x: (x[1], -x[0])) # <-- 2)\n\n return chain(*[[n]* cnt for n,cnt in arr]) # <-- 3)\n```\n[https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330070571/](https://leetcode.com/problems/sort-array-by-increasing-frequency/submissions/1330070571/)\n\nI could be wrong, but I think that time complexity is *O*(*N* log *N*) and space complexity is *O*(*N*), in which *N* ~ `len(nums)`.\n\n
9
0
['Python', 'Python3']
0
sort-array-by-increasing-frequency
One Line Code Python
one-line-code-python-by-ganjinaveen-8s6g
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
GANJINAVEEN
NORMAL
2023-03-04T21:57:54.420282+00:00
2023-03-04T21:57:54.420308+00:00
1,038
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sorted(sorted(nums,reverse=True),key=nums.count)\n#please upvote me it would encourage me alot\n\n```
9
0
['Python3']
0
sort-array-by-increasing-frequency
0ms !!!! Lowest Complexity and Easy to Understand
0ms-lowest-complexity-and-easy-to-unders-9mli
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
parshanth2005
NORMAL
2024-07-23T07:49:41.941859+00:00
2024-07-23T07:49:41.941897+00:00
1,724
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.*;\n\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> frequencyMap = new HashMap<>();\n for (int num : nums) {\n frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);\n }\n\n List<Integer> numList = new ArrayList<>();\n for (int num : nums) {\n numList.add(num);\n }\n\n Collections.sort(numList, (a, b) -> {\n int freqA = frequencyMap.get(a);\n int freqB = frequencyMap.get(b);\n if (freqA != freqB) {\n return Integer.compare(freqA, freqB);\n } else {\n return Integer.compare(b, a);\n }\n });\n\n for (int i = 0; i < nums.length; i++) {\n nums[i] = numList.get(i);\n }\n\n return nums;\n }\n}\n\n```
8
0
['Java']
6
sort-array-by-increasing-frequency
Sort Array by Increasing Frequency
sort-array-by-increasing-frequency-by-ma-xfor
Approach\nStep 1: Counting Frequencies\n\nPurpose: This step counts the frequency of each element in the nums array using a HashMap. The key of the map is the e
MananJain13
NORMAL
2024-07-23T04:58:00.828503+00:00
2024-07-23T04:58:00.828525+00:00
1,912
false
# Approach\nStep 1: Counting Frequencies\n\nPurpose: This step counts the frequency of each element in the nums array using a HashMap. The key of the map is the element itself, and the value is the frequency of that element.\n\nExplanation:\nLoop through each element in the nums array.\nIf the element is already present in the map, increment its count by 1.\nIf the element is not present, add it to the map with a frequency of 1.\n\nStep 2: Creating a List of Unique Numbers\n\nPurpose: Create a list of unique numbers from the keys of the frequency map. This list will be sorted based on the required criteria.\n\nExplanation:\nThe keySet() method of the map returns a set of all keys, which are the unique numbers in the array.\nThis set is used to initialize an ArrayList, allowing us to sort the unique numbers later.\n\nStep 3: Sorting the List\nPurpose: Sort the list of unique numbers based on their frequency, with ties broken by sorting in decreasing order.\n\nExplanation:\nThe Collections.sort() method is used with a custom comparator to define the sorting behavior.\nComparator Logic:\nIf the frequencies of two numbers a and b are equal (map.get(a) == map.get(b)), sort them in descending order (b - a).\nOtherwise, sort them in ascending order of their frequency (map.get(a) - map.get(b)).\n\nStep 4: Constructing the Result Array\n\nPurpose: Construct the final sorted array based on the sorted list of unique numbers and their frequencies.\n\nExplanation:\nAn array result of the same length as nums is created to store the final sorted elements.\nLoop through each number in the sorted list.\nFor each number, append it to the result array according to its frequency stored in the map.\nIncrement the index variable to fill the result array correctly.\n\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map=new HashMap<Integer, Integer>();\n for(int i=0;i<nums.length;i++){\n if(map.containsKey(nums[i])){\n map.put(nums[i],map.get(nums[i])+1);\n }\n else{\n map.put(nums[i],1);\n }\n }\n\n List<Integer> list=new ArrayList<Integer>(map.keySet());\n Collections.sort(list,(a,b)->{\n if(map.get(a)==map.get(b)){\n return b - a;\n }\n else{\n return map.get(a) - map.get(b);\n }\n });\n int[] result=new int[nums.length];\n int index=0;\n for(int num:list){\n for(int i=0;i<map.get(num);i++){\n result[index++]=num;\n }\n }\n return result;\n }\n}\n```\n
8
0
['Java']
3
sort-array-by-increasing-frequency
Best Solution with proper explanation. Beats 100% and 0ms. Trust:)
best-solution-with-proper-explanation-be-51rj
Intuition\n Describe your first thoughts on how to solve this problem. \nFirst map a map, then sort the nums array acoording to the values in the map\n# Approac
sehaj_s5
NORMAL
2024-07-23T04:22:19.229625+00:00
2024-07-23T04:22:19.229657+00:00
773
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst map a map, then sort the nums array acoording to the values in the map\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- make a map, iterate through the nums array and store the frequencies in the map\n- sort the nums array according to the lambda function where\n- - if the frequencing are same, return if the first value is bigger than the secon\n- - else return true if the frequency of first element is greater than the frequency of second.\n- return the newly sorted array \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$- making the map\n$$O(nlogn)$$- for sorting \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$- due to the space the map takes\n# Code\n```\nfunc frequencySort(nums []int) []int {\n mapp:= make(map[int]int)\n n:= len(nums)\n if n==1{\n return nums\n }\n for i:=0;i<n;i++{\n mapp[nums[i]]++\n }\n sort.Slice(nums, func(i, j int)bool{\n if mapp[nums[i]]==mapp[nums[j]]{\n return nums[i]>nums[j]\n }\n return mapp[nums[i]]<mapp[nums[j]]\n })\n return nums\n}\n```\n\nIf you found this helpful, kindly upvote, the button is on the bottom left corner.
8
0
['Array', 'Hash Table', 'Sorting', 'C++', 'Go']
1
sort-array-by-increasing-frequency
Hash Table with Custom Compare Function | C++, Python, Java
hash-table-with-custom-compare-function-j3khg
Approach\n Describe your approach to solving the problem. \nWe can use a hashmap (or an array) freq to map each value in nums to their frequencies, then use a c
not_yl3
NORMAL
2024-07-23T00:17:54.859465+00:00
2024-07-23T22:47:01.241736+00:00
5,849
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use a hashmap (or an array) `freq` to map each value in `nums` to their frequencies, then use a custom compare function to sort them based on their frequencies. For the custom compare function we must remember that if two numbers have the same frequency, the greater one comes first in the sorted list. Otherwise, all the values are sorted by increasing frequency.\n# Complexity\n- Time complexity: $$O(n(log(n)))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n int freq[201] = {}; // Array to store frequency of each number\n // Guaranteed to be -100 to 100 so we add 100 for negative numbers\n for (int num : nums)\n freq[num + 100]++;\n sort(nums.begin(), nums.end(), [&freq](int a, int b){\n return freq[a + 100] == freq[b + 100] ? a > b : freq[a + 100] < freq[b + 100];\n }); // If the frequency of a and b are equal, we compare the values, otherwise we compare the frequencies and return the lesser one\n return nums;\n }\n};\n```\n```python []\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq = Counter(nums) # Returns a dictionary with every unique element in nums mapped to their frequency in the list\n return sorted(nums, key=lambda x: (freq[x], -x)) # Returns a tuple in the form (frequency, -value).\n # This sorts first by frequency, but if they are equal, it then compares\n # the values. However, we change to negative so larger values will be first since it sorts in ascending order by default\n```\n```Java []\nclass Solution {\n public int[] frequencySort(int[] nums) {\n int[] freq = new int[201]; // Array to store frequency of each number\n // Guaranteed to be -100 to 100 so we add 100 for negative numbers\n List<Integer> list = new ArrayList<>(); // Array list so we can use a custom copare functions with the sort methods in the collections class\n for (int num : nums){\n freq[num + 100]++;\n list.add(num);\n }\n Collections.sort(list, (a, b) -> {\n return freq[a + 100] == freq[b + 100] ? b - a : freq[a + 100] - freq[b + 100];\n }); // If the frequency of a and b are equal, we compare the values, otherwise we compare the frequencies and return the lesser one\n for (int i = 0; i < nums.length; i++)\n nums[i] = list.get(i);\n return nums;\n }\n}\n```\n
8
0
['Array', 'Hash Table', 'C', 'Sorting', 'Python', 'C++', 'Java', 'Python3']
9
sort-array-by-increasing-frequency
java easy to understand solution
java-easy-to-understand-solution-by-aksh-txxy
-> The idea is to use hashmap for storing frequency of the values and then iterate over hashmap and store values and their frequency in 2d array then sort the 2
Akshat_Mathur
NORMAL
2022-01-26T12:33:00.741506+00:00
2024-07-07T09:28:31.739155+00:00
1,649
false
-> The idea is to use hashmap for storing frequency of the values and then iterate over hashmap and store values and their frequency in 2d array then sort the 2d array on the basis of two columns and then fill the new ans[] array and return it.\n-> We will sort the array on the basis of two columns because values having equal frequencies should be sorted in decreasing order.\n-> So, we will first sort the 2d array on the basis of values (decreasing order) and then on the basis of frequency (increasing order).\n******Please Please...... upvote if it helps you to solve the problem******* as it motivates me to post solutions.\n \n\tpublic int[] frequencySort(int[] nums) {\n\t\t //hashmap for storing frequency of the values\n HashMap<Integer,Integer> hm = new HashMap<>();\n \n\t\tint c = 0; //for counting distinct values \n for(int i=0;i<nums.length;i++){\n if(hm.containsKey(nums[i])){\n int v = hm.get(nums[i]);\n v++;\n hm.put(nums[i],v);\n }else{\n hm.put(nums[i],1);\n c++;\n }\n }\n\t\t\n int[][] arr = new int[c][2]; //2d array which contains values in first column and frequency in second column\n\t\t\n\t\t//iterate over hashmap to store value and frequency in 2d array\n int i=0;\n\t\tfor(Map.Entry<Integer,Integer> entry:hm.entrySet()){\n arr[i][0] = entry.getKey();\n arr[i][1] = entry.getValue();\n i++;\n }\n\t\t// values are sorted in decreasing order as per given in the question\n Arrays.sort(arr,(a,b)->b[0]-a[0]);\n\t\t\n\t\t//frequency in increasing order\n Arrays.sort(arr,(a,b)->a[1]-b[1]); \n \n\t\tint[] ans = new int[nums.length]; //ans array to return the answer\n int j=0;\n for(i=0;i<arr.length;i++){\n int count = 0;\n while(count<arr[i][1]){\n ans[j] = arr[i][0];\n j++;\n count++;\n }\n }\n return ans;\n }\n\t}```
8
2
['Array', 'Hash Table', 'Sorting', 'Java']
2
sort-array-by-increasing-frequency
✅ Java - Simple HashMap & PriorityQueue Solution
java-simple-hashmap-priorityqueue-soluti-nw71
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n //init hashmap and count occurences of elements in nums\n //init minHeap based
welcomecurry
NORMAL
2021-04-03T03:57:21.487893+00:00
2021-04-05T04:08:50.859234+00:00
1,756
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n //init hashmap and count occurences of elements in nums\n //init minHeap based on occurence, if two elements have same freq sort in decreasing order\n //add elements in map into minHeap as array, containing element and occurence\n\t\t//init index to traverse array\n //loop while minHeap is not empty\n //grab min element \n //keep inserting element into nums while in bounds and occurence > 0\n //return nums\n \n Map<Integer, Integer> map = new HashMap<>();\n \n for(int i : nums)\n {\n map.put(i, map.getOrDefault(i, 0) + 1);\n }\n \n PriorityQueue<int[]> minHeap = new PriorityQueue<>((a,b) -> a[1] == b[1] ? b[0] - a[0] : a[1] - b[1]);\n \n for(Map.Entry<Integer, Integer> entry : map.entrySet())\n {\n minHeap.add(new int[] {entry.getKey(), entry.getValue()});\n }\n \n int index = 0;\n \n while(!minHeap.isEmpty())\n {\n int[] min = minHeap.poll();\n \n while(index < nums.length && min[1] > 0)\n {\n nums[index++] = min[0];\n min[1]--;\n }\n }\n \n return nums;\n }\n}\n```
8
0
['Heap (Priority Queue)', 'Java']
3
sort-array-by-increasing-frequency
C++ simple and short with custom comparator lambda function
c-simple-and-short-with-custom-comparato-7kh6
\nvector<int> frequencySort(vector<int>& nums) {\n\tmap<int, int> freq;\n\tfor (int n : nums)\n\t\tfreq[n]++;\n\tsort(nums.begin(), nums.end(),\n\t\t\t[&freq](c
oleksam
NORMAL
2020-12-06T11:34:32.194649+00:00
2020-12-06T17:54:20.509141+00:00
1,721
false
```\nvector<int> frequencySort(vector<int>& nums) {\n\tmap<int, int> freq;\n\tfor (int n : nums)\n\t\tfreq[n]++;\n\tsort(nums.begin(), nums.end(),\n\t\t\t[&freq](const int& a, const int& b) {\n\t\t\t\treturn (freq[a] == freq[b]) ? a > b : freq[a] < freq[b];\n\t});\n\treturn nums;\n}\n```\n
8
0
['C', 'C++']
2
sort-array-by-increasing-frequency
HashMap Solution
hashmap-solution-by-pranay-code24-ypyi
# Intuition \n\n\n# Approach : Using HashMap and Sorting\n\n\n# Complexity\n- Time complexity: O(nlogn)\n\n\n- Space complexity: O(n)\n\n\n# Code\n\nclass Sol
pranay_code24
NORMAL
2024-07-23T03:45:27.589225+00:00
2024-07-23T03:45:27.589253+00:00
1,103
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : Using HashMap and Sorting\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n HashMap<Integer, Integer> map = new HashMap<>();\n List<Integer> list = new ArrayList<>();\n for(int n : nums) {\n list.add(n);\n map.put(n, map.getOrDefault(n, 0) + 1);\n }\n Collections.sort(list, (a, b) ->\n (map.get(a) == map.get(b)) ? b-a : map.get(a)-map.get(b));\n return list.stream().mapToInt(Integer::intValue).toArray();\n }\n}\n```
7
0
['Array', 'Hash Table', 'Sorting', 'Java']
2
sort-array-by-increasing-frequency
C solution using qsort
c-solution-using-qsort-by-duckbill360-ygfs
\n// Let it be global to be used in cmp(). \nint count[201];\n\nint cmp(const void *a, const void *b){\n if(count[*(int*)a + 100] != count[*(int*)b + 100])\n
duckbill360
NORMAL
2021-12-16T02:59:50.834925+00:00
2021-12-16T02:59:50.834957+00:00
605
false
```\n// Let it be global to be used in cmp(). \nint count[201];\n\nint cmp(const void *a, const void *b){\n if(count[*(int*)a + 100] != count[*(int*)b + 100])\n return count[*(int*)a + 100] > count[*(int*)b + 100];\n else\n return *(int*)a < *(int*)b;\n}\n\nint* frequencySort(int* nums, int numsSize, int* returnSize){\n int i, l = numsSize;\n memset(count, 0, sizeof(count));\n \n for(i = 0; i < l; i++){\n count[nums[i] + 100]++;\n }\n \n qsort(nums, l, sizeof(int), cmp);\n *returnSize = l;\n \n return nums;\n}\n```
7
0
['C']
0
sort-array-by-increasing-frequency
Bucket Sort
bucket-sort-by-jjqq-dtcu
I know the answer can be in several lines...but during a real interview, what is the interverer expected to see? More from algorithm level, to evaluate your alg
jjqq
NORMAL
2021-11-15T06:34:51.525916+00:00
2021-11-15T06:34:51.525948+00:00
715
false
I know the answer can be in several lines...but during a real interview, what is the interverer expected to see? More from algorithm level, to evaluate your algorithm skills (instead of checking how many default libraries/built-in you can remember)?\n\nHere is a pure bucket sort...\n\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n if (nums.length == 1) {\n return nums;\n }\n \n int[] result = new int[nums.length];\n Map<Integer, Integer> numCountMap = new HashMap<>();\n int maxCount = 0;\n \n for (int num : nums) {\n int count = numCountMap.getOrDefault(num, 0);\n count++;\n maxCount = Math.max(maxCount, count);\n numCountMap.put(num, count);\n }\n \n List<Integer>[] bucket = new List[maxCount + 1];\n \n for (Map.Entry<Integer, Integer> entry : numCountMap.entrySet()) {\n int num = entry.getKey();\n int count = entry.getValue();\n \n List<Integer> tempList;\n \n if (bucket[count] == null) {\n tempList = new ArrayList<>();\n } else {\n tempList = bucket[count];\n }\n \n tempList.add(num);\n bucket[count] = tempList;\n }\n \n int p = 0;\n for (int i = 1; i <= bucket.length - 1; i++) {\n List<Integer> list = bucket[i];\n if (list != null) {\n Collections.sort(list, Collections.reverseOrder());\n for (Integer num : list) {\n int count = i;\n while(count > 0) {\n result[p] = num;\n p++;\n count--;\n }\n }\n }\n }\n \n return result;\n }\n}\n```
7
0
['Bucket Sort', 'Java']
0
sort-array-by-increasing-frequency
Faster than 95% using lambda function and sort
faster-than-95-using-lambda-function-and-m3bp
\nfrom collections import Counter\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n \n di=Counter(nums)\n li=l
ana_2kacer
NORMAL
2021-06-20T20:19:05.712320+00:00
2021-06-20T20:19:05.712359+00:00
1,279
false
```\nfrom collections import Counter\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n \n di=Counter(nums)\n li=list(di.items())\n \n #keep a list of frequency elements and their values[val,freq]\n \n li.sort(key=lambda x:(x[1],-x[0]))\n \n #LARGEST POSITIVE NUMBER IS SMALLEST NEGATIVE NUMBER\n res=[]\n for val,freq in (li):\n res+=[val]*freq\n return res\n\t\t\n```\n\tAfter making list of frequency and values, we sort the list using custom lambda function.\nIn case the frequency is same, the value is sorted in reverse(as we consider it a negative value).
7
0
['Sorting', 'Python', 'Python3']
2
sort-array-by-increasing-frequency
C++ Soln || Beats 100% 🔥|| Easy || Comparator || Lambda Function
c-soln-beats-100-easy-comparator-lambda-7vj8m
Intuition\nThe goal of this problem is to sort the elements of the array based on their frequency in ascending order. If two elements have the same frequency, t
kk_the_omniscient
NORMAL
2024-07-23T04:28:21.893781+00:00
2024-07-23T04:28:21.893813+00:00
1,814
false
# Intuition\nThe goal of this problem is to sort the elements of the array based on their frequency in ascending order. If two elements have the same frequency, they should be sorted by their value in descending order. This ensures that less frequent elements appear earlier, and for elements with the same frequency, the larger values come first.\n\n# Approach\n1) Frequency Counting: Use an unordered_map to count the frequency of each element in the input vector nums.\n2) Custom Sorting: Sort the input vector using a custom comparator. The comparator checks the frequency of the elements from the map:\n- If two elements have the same frequency, the comparator returns true if the first element is greater than the second, ensuring larger values come first.\n- If two elements have different frequencies, the comparator returns true if the frequency of the first element is less than the frequency of the second, ensuring lower frequencies come first.\n3) Return Result: The sorted vector is returned as the result.\n\n# Complexity\n- Time complexity:O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> map;\n for (auto i : nums) {\n map[i]++;\n }\n sort(nums.begin(), nums.end(), [&map](int a, int b) {\n if (map[a] == map[b]) {\n return a > b;\n }\n return map[a] < map[b];\n });\n return nums;\n }\n};\n\n```
6
0
['C++']
0
sort-array-by-increasing-frequency
C# Solution for Sort Array In Increasing Frequency Problem
c-solution-for-sort-array-in-increasing-bq596
Intuition\n Describe your first thoughts on how to solve this problem. \nIn C#, we can use a Dictionary for counting frequencies, followed by a sorted list to m
Aman_Raj_Sinha
NORMAL
2024-07-23T03:45:42.713483+00:00
2024-07-23T03:45:42.713503+00:00
621
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn C#, we can use a Dictionary for counting frequencies, followed by a sorted list to maintain the elements by their frequency. Here\u2019s\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tCount Frequencies: Use a Dictionary<int, int> to store the frequency of each element.\n2.\tGroup by Frequency: Use another Dictionary<int, List<int>> to group elements by their frequency.\n3.\tSort Groups: Sort the keys of the frequency groups in ascending order and within each frequency group, sort the elements in descending order.\n4.\tConstruct Result: Iterate over the sorted frequency groups to construct the result array.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1.\tCounting Frequencies: This takes O(n) time.\n2.\tGrouping by Frequency: This takes O(n) time.\n3.\tSorting Groups: Sorting the frequency keys takes O(k log k) , where k is the number of unique frequencies. Sorting the elements within each frequency group takes O(u log u) for each group, where u is the number of unique elements with that frequency. In the worst case, this can be O(n log n) .\n4.\tConstructing Result: This takes O(n) time.\n\nThus, the overall time complexity is O(n log n) .\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1.\tDictionary for Frequency Count: This requires O(n) space in the worst case.\n2.\tDictionary for Grouping by Frequency: This also requires O(n) space.\n3.\tList for Sorted Numbers: This requires O(n) space.\n\nThus, the overall space complexity is O(n) .\n\n# Code\n```\npublic class Solution {\n public int[] FrequencySort(int[] nums) {\n // Step 1: Count the frequency of each element\n var freqMap = new Dictionary<int, int>();\n foreach (var num in nums) {\n if (freqMap.ContainsKey(num)) {\n freqMap[num]++;\n } else {\n freqMap[num] = 1;\n }\n }\n\n // Step 2: Group elements by their frequency\n var groupedByFreq = new Dictionary<int, List<int>>();\n foreach (var kvp in freqMap) {\n var num = kvp.Key;\n var freq = kvp.Value;\n if (!groupedByFreq.ContainsKey(freq)) {\n groupedByFreq[freq] = new List<int>();\n }\n groupedByFreq[freq].Add(num);\n }\n\n // Step 3: Sort the groups by frequency and sort the elements in each group in descending order\n var sortedNums = new List<int>();\n foreach (var freq in groupedByFreq.Keys.OrderBy(f => f)) {\n var numsWithSameFreq = groupedByFreq[freq];\n numsWithSameFreq.Sort((a, b) => b.CompareTo(a)); // Descending order\n foreach (var num in numsWithSameFreq) {\n for (int i = 0; i < freq; i++) {\n sortedNums.Add(num);\n }\n }\n }\n\n return sortedNums.ToArray();\n }\n}\n```
6
0
['C#']
1
sort-array-by-increasing-frequency
Aditya Verma Approach || Easy to understand
aditya-verma-approach-easy-to-understand-q8t0
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
yc06311
NORMAL
2023-08-08T14:14:28.157911+00:00
2023-08-08T14:14:28.157938+00:00
860
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> m;\n for(auto it : nums) m[it]++;\n\n priority_queue<pair<int,int>> h; \n for(auto &i:m) h.push({-i.second,i.first});\n \n vector<int> v;\n while(!h.empty())\n {\n for(int i = 0; i<-(h.top().first); i++)\n {\n v.push_back(h.top().second);\n }\n h.pop();\n }\n return v;\n }\n};\n```
6
0
['C++']
2
sort-array-by-increasing-frequency
Java Most Possible Solution
java-most-possible-solution-by-janhvi__2-lzcr
\n# Complexity\n- Time complexity:O(N^2)\n Add your time complexity here, e.g. O(n) \n\n# Code\n\nclass Solution {\n public int[] frequencySort(int[] nums) {
Janhvi__28
NORMAL
2022-12-15T17:35:05.899188+00:00
2022-12-15T17:35:05.899226+00:00
2,417
false
\n# Complexity\n- Time complexity:O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n int[] cnt = new int[201];\n List<Integer> t = new ArrayList<>();\n for (int v : nums) {\n v += 100;\n ++cnt[v];\n t.add(v);\n }\n t.sort((a, b) -> cnt[a] == cnt[b] ? b - a : cnt[a] - cnt[b]);\n int[] ans = new int[nums.length];\n int i = 0;\n for (int v : t) {\n ans[i++] = v - 100;\n }\n return ans;\n }\n}\n```
6
0
['Java']
0
sort-array-by-increasing-frequency
Easy C++ Solution using unordered_map
easy-c-solution-using-unordered_map-by-t-lnwa
\n# Code\n\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> mp;\n for(int i : nums){\n
tata32000
NORMAL
2022-12-03T14:57:28.179582+00:00
2022-12-03T14:57:28.179603+00:00
1,425
false
\n# Code\n```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> mp;\n for(int i : nums){\n mp[i]++;\n }\n sort(nums.begin(), nums.end(), [&](int n1, int n2){\n if(mp[n1] == mp[n2]){\n return n1 > n2;\n }\n return mp[n1] < mp[n2];\n });\n return nums;\n }\n};\n```
6
0
['Hash Table', 'Sorting', 'C++']
0
sort-array-by-increasing-frequency
C++ solution || Using Priority queue || Beginner friendly
c-solution-using-priority-queue-beginner-cg62
I have used unordered map instead of ordered map because insertion of an element in unordered map is O(1) time complexity.\n\n vector<int> frequencySort(vector<
jumboclif42
NORMAL
2022-03-22T15:49:04.293705+00:00
2022-03-23T04:04:59.351400+00:00
312
false
``` I have used unordered map instead of ordered map because insertion of an element in unordered map is O(1) time complexity.```\n```\n vector<int> frequencySort(vector<int>& a) {\n int n=a.size();\n vector<int>v;\n unordered_map<int,int>mp;\n for(int i=0;i<n;i++)\n mp[a[i]]++;\n priority_queue<pair<int,int>>pq;\n for(auto it:mp)\n pq.push({-(it.second),(it.first)}); // (-) sign is used to make it a min heap.\n while(!pq.empty()) { \n int num1= -pq.top().first; \n\t\t\t int num2 = pq.top().second; \n while(num1--)\n\t\t\t v.push_back(num2);\n\n\t\t\tpq.pop();\n\t\t}\n return v;\n }\n```\n```If you like my approach then please upvote me.```
6
0
[]
3
sort-array-by-increasing-frequency
C++ || Map and Priority Queue
c-map-and-priority-queue-by-gunjan-g-uxkl
Approach: Use an unordered map for storing frequency of numbers present. Then, a priority queue with custom comparator class is used to store the numbers accord
gunjan-g
NORMAL
2022-01-14T16:17:00.192896+00:00
2022-01-20T06:45:09.325965+00:00
598
false
Approach: Use an unordered map for storing frequency of numbers present. Then, a priority queue with custom comparator class is used to store the numbers accordingly. Here is the code implementation.\n\n```\nclass compare{\n public:\n bool operator()(pair<int,int> n1, pair<int,int> n2){\n if(n1.second==n2.second){\n return n1.first<n2.first;\n }\n return n1.second>n2.second;\n }\n};\n\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n vector<int> res;\n unordered_map<int,int> m;\n for(int i=0;i<nums.size();i++){\n m[nums[i]]++;\n }\n \n priority_queue<pair<int,int>, vector<pair<int,int>>, compare> pq;\n for(auto x: m){\n pq.push({x.first, x.second});\n }\n \n while(!pq.empty()){\n while(m[pq.top().first]>0){\n res.push_back(pq.top().first);\n m[pq.top().first]--;\n }\n pq.pop();\n }\n return res;\n }\n};\n```\n\n**Please upvote!**
6
1
['C', 'Heap (Priority Queue)']
2
sort-array-by-increasing-frequency
[Python] Sort on (count,-value), 3 Lines
python-sort-on-count-value-3-lines-by-ra-h4e0
Have the sort key be the count of occurrences, and the negative of the value. O(nlogn),O(n) time and space.\n\n\nclass Solution:\n def frequencySort(self, nu
raymondhfeng
NORMAL
2020-10-31T16:02:21.255787+00:00
2020-10-31T16:02:21.255829+00:00
727
false
Have the sort key be the count of occurrences, and the negative of the value. O(nlogn),O(n) time and space.\n\n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n counter = collections.Counter(nums)\n nums.sort(key=lambda x: (counter[x],-x))\n return nums\n```
6
2
[]
4
sort-array-by-increasing-frequency
🔢💯 Ace Frequency Sorting! 🚀✨ Simple & Effective Python Solution! 🎓🔥
ace-frequency-sorting-simple-effective-p-fmxe
Intuition\n Describe your first thoughts on how to solve this problem. \nTo sort elements of an array based on their frequency and then by their value in decrea
LinhNguyen310
NORMAL
2024-07-23T14:11:50.283049+00:00
2024-07-23T14:11:50.283087+00:00
333
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo sort elements of an array based on their frequency and then by their value in decreasing order if frequencies are the same, we can use a frequency dictionary to keep track of how often each number appears. Then, we can use this information to construct the sorted array as required.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount Frequencies: Use a dictionary to count the frequency of each element in the input list.\nGroup by Frequency: Use another dictionary to group elements by their frequencies.\nSort by Frequency and Value:\nFirst, sort the elements by their frequency in ascending order.\nIf two elements have the same frequency, sort them by their value in descending order.\nConstruct Result: Based on the sorted frequency groups, construct the result list.\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def frequencySort(self, nums):\n """\n :type nums: List[int]\n :rtype: List[int]\n """\n frequencyDict, numDict = {}, {}\n ret = []\n\n for num in nums:\n if num in numDict:\n numDict[num] += 1\n else:\n numDict[num] = 1\n\n for key, val in numDict.items():\n if val in frequencyDict:\n frequencyDict[val] += [key]\n else:\n frequencyDict[val] = [key]\n\n frequencyDict = sorted(frequencyDict.items())\n for item in frequencyDict:\n [frequency, numList] = item\n numList.sort(reverse=True)\n for num in numList:\n temp = [num] * frequency\n ret += temp\n return ret\n```\n\n![packied_spongebob.jpg](https://assets.leetcode.com/users/images/3d1a5355-c3b0-4561-bc1a-b4dc0d89adb1_1721743798.6866136.jpeg)\n
5
0
['Python']
1
sort-array-by-increasing-frequency
beat 98.94% 🔥🔥🔥
beat-9894-by-ahmed_kazi-6tvh
\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
Ahmed_Kazi
NORMAL
2024-07-23T09:31:46.721909+00:00
2024-07-23T09:31:46.721936+00:00
158
false
![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
5
0
['JavaScript']
0
sort-array-by-increasing-frequency
JAVA Solution Explained in HINDI
java-solution-explained-in-hindi-by-the_-dvt6
https://youtu.be/-WWyNaS1lVk\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote
The_elite
NORMAL
2024-07-23T06:17:53.279509+00:00
2024-07-23T06:17:53.279532+00:00
537
false
https://youtu.be/-WWyNaS1lVk\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\n# Subscribe:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\n## Subscribe Goal:- 600\n## Current Subscriber:- 505\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n \n Map<Integer, Integer> freq = new HashMap<>();\n for(int num : nums) {\n freq.put(num, freq.getOrDefault(num, 0) + 1);\n }\n\n Integer[] numsObj = new Integer[nums.length];\n for(int i = 0; i < nums.length; i++) {\n numsObj[i] = nums[i];\n }\n\n Arrays.sort(numsObj, (a, b) -> {\n if(freq.get(a).equals(freq.get(b))) {\n return Integer.compare(b, a);\n }\n return Integer.compare(freq.get(a), freq.get(b));\n });\n\n for(int i = 0; i < nums.length; i++) {\n nums[i] = numsObj[i];\n }\n\n return nums;\n }\n}\n```
5
0
['Java']
1
sort-array-by-increasing-frequency
🌟🔥 Easy Solution and Detailed Explanation || ✅ C++ || ✅ Java || ✅ Python 🔥🌟
easy-solution-and-detailed-explanation-c-0lmt
Approach\n### Step 1: Counting Frequencies \uD83D\uDCCA\nWe start by creating a HashMap to count the frequency of each element in the array.\n\njava\nHashMap<In
originalpandacoder
NORMAL
2024-07-23T03:38:47.985526+00:00
2024-07-23T03:38:47.985559+00:00
1,933
false
# Approach\n### Step 1: Counting Frequencies \uD83D\uDCCA\nWe start by creating a `HashMap` to count the frequency of each element in the array.\n\n```java\nHashMap<Integer, Integer> map = new HashMap<>();\nfor (int i = 0; i < nums.length; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);\n}\n```\n- **Explanation:** This loop iterates over the array `nums`, and for each element, it increments its count in the `map`. If the element is not present in the map, `getOrDefault` initializes it with `0`.\n\n### Step 2: Convert to Integer Array \uD83D\uDD04\nNext, we convert the `int` array to an `Integer` array to use `Arrays.sort` with a custom comparator.\n\n```java\nInteger[] arrobj = new Integer[nums.length];\nfor (int i = 0; i < nums.length; i++) {\n arrobj[i] = nums[i];\n}\n```\n- **Explanation:** We create a new `Integer` array `arrobj` and copy each element from the `nums` array into `arrobj`.\n\n### Step 3: Custom Sorting \uD83D\uDCDA\nWe sort the `arrobj` array based on the custom comparator:\n- By frequency in ascending order.\n- By value in descending order if frequencies are the same.\n\n```java\nArrays.sort(arrobj, (a, b) -> {\n if (map.get(a).equals(map.get(b))) {\n return Integer.compare(b, a); // Sort by value in descending order if frequencies are the same\n }\n return Integer.compare(map.get(a), map.get(b)); // Sort by frequency in ascending order\n});\n```\n- **Explanation:** We define a custom comparator:\n - If two elements have the same frequency (`map.get(a).equals(map.get(b))`), we sort them by their value in descending order (`Integer.compare(b, a)`).\n - Otherwise, we sort them by their frequency in ascending order (`Integer.compare(map.get(a), map.get(b))`).\n\n### Step 4: Convert Back to int Array \uD83D\uDD04\nFinally, we convert the sorted `Integer` array back to the `int` array to return the result.\n\n```java\nfor (int i = 0; i < nums.length; i++) {\n nums[i] = arrobj[i];\n}\n\nreturn nums;\n```\n- **Explanation:** We copy each element from the `arrobj` array back into the `nums` array.\n\n### Full Code Implementation \uD83D\uDCDD\n```C++ []\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nclass Solution {\npublic:\n std::vector<int> frequencySort(std::vector<int>& nums) {\n // \uD83D\uDCCA Create an unordered_map to store the frequency of each element\n std::unordered_map<int, int> map;\n for (int num : nums) {\n map[num]++;\n }\n\n // \uD83D\uDCDA Sort the array based on the custom comparator\n std::sort(nums.begin(), nums.end(), [&map](int a, int b) {\n if (map[a] == map[b]) {\n return a > b; // Sort by value in descending order if frequencies are the same\n }\n return map[a] < map[b]; // Sort by frequency in ascending order\n });\n\n return nums;\n }\n};\n\n```\n```java []\nimport java.util.*;\n\nclass Solution {\n public int[] frequencySort(int[] nums) {\n // \uD83D\uDCCA Create a hashmap to store the frequency of each element\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);\n }\n\n // \uD83D\uDD04 Convert the array to an Integer array to use Arrays.sort with a custom comparator\n Integer[] arrobj = new Integer[nums.length];\n for (int i = 0; i < nums.length; i++) {\n arrobj[i] = nums[i];\n }\n\n // \uD83D\uDCDA Sort the array based on the custom comparator\n Arrays.sort(arrobj, (a, b) -> {\n if (map.get(a).equals(map.get(b))) {\n return Integer.compare(b, a); // Sort by value in descending order if frequencies are the same\n }\n return Integer.compare(map.get(a), map.get(b)); // Sort by frequency in ascending order\n });\n\n // \uD83D\uDD04 Convert the sorted array back to int array\n for (int i = 0; i < nums.length; i++) {\n nums[i] = arrobj[i];\n }\n\n return nums;\n }\n}\n```\n```python []\nfrom collections import Counter\n\nclass Solution:\n def frequencySort(self, nums):\n # \uD83D\uDCCA Create a Counter to store the frequency of each element\n count = Counter(nums)\n\n # \uD83D\uDCDA Sort the array based on the custom comparator\n nums.sort(key=lambda x: (count[x], -x))\n\n return nums\n\n```\n![UP.png](https://assets.leetcode.com/users/images/1ee5263a-0285-4918-bfda-5df001bd1796_1721705785.7250383.png)\n
5
0
['Array', 'Hash Table', 'Sorting', 'Python', 'C++', 'Java']
4
sort-array-by-increasing-frequency
Counting with Bucket Sort | Python
counting-with-bucket-sort-python-by-prag-mvag
Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n
pragya_2305
NORMAL
2024-07-23T02:47:48.434858+00:00
2024-07-23T02:47:48.434882+00:00
325
false
# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n count = Counter(nums) #O(n)\n freq = [[] for _ in range(len(nums)+1)] #O(n)\n\n for key,val in count.items(): #O(n)\n freq[val].append(key)\n\n res = []\n for i,l in enumerate(freq): #O(nlogn)\n for item in sorted(l,reverse=True):\n res+=[item]*i\n \n return res\n\n```
5
0
['Array', 'Hash Table', 'Sorting', 'Python', 'Python3']
1
sort-array-by-increasing-frequency
✅ Simple Heap Solution | Python
simple-heap-solution-python-by-rhuang53-htnt
Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n\nfrom collections import Counter\nfrom heapq import heappop, heappush\nclass Sol
rhuang53
NORMAL
2024-07-23T00:57:09.339749+00:00
2024-07-23T00:57:09.339780+00:00
466
false
# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n)\n\n# Code\n```\nfrom collections import Counter\nfrom heapq import heappop, heappush\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n freq = Counter(nums)\n\n heap = []\n for num in freq:\n heappush(heap, (freq[num], -num))\n\n output = []\n while heap:\n f, n = heappop(heap)\n for i in range(f):\n output.append(-n)\n \n return output\n \n\n```
5
0
['Array', 'Sorting', 'Heap (Priority Queue)', 'Python3']
1
sort-array-by-increasing-frequency
Java | No maps, only arrays | Sorting | Clean code
java-no-maps-only-arrays-sorting-clean-c-vcvc
Complexity\n- Time complexity: O(n*log(n))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \
judgementdey
NORMAL
2024-07-23T00:17:06.458663+00:00
2024-07-23T00:17:06.458693+00:00
4,227
false
# Complexity\n- Time complexity: $$O(n*log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n var freq = new int[201][2];\n\n for (var i=0; i<201; i++)\n freq[i][0] = i - 100;\n\n for (var a : nums)\n freq[a + 100][1]++;\n\n Arrays.sort(freq, (a, b) -> a[1] == b[1] ? Integer.compare(b[0], a[0]) : Integer.compare(a[1], b[1]));\n\n var k = 0;\n for (var i=0; i<201; i++)\n for (var j = 0; j < freq[i][1]; j++)\n nums[k++] = freq[i][0];\n\n return nums;\n }\n}\n```\nIf you like my solution, please upvote it!
5
0
['Array', 'Sorting', 'Java']
4
sort-array-by-increasing-frequency
Concise LINQ solution
concise-linq-solution-by-dungtranm65-b8e1
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nWith C# you can make us
dungtranm65
NORMAL
2023-11-16T02:56:59.402072+00:00
2023-11-16T02:56:59.402095+00:00
163
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWith C# you can make use of LINQ. For this problem, LINQ can provide a concise solution with each method in the chain is self-explaind and following the stated requirement step by step (GroupBy / Count -> Order by Count -> then by Decreasing value)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIf we break down:\n 1. GroupBy: internally should do loop through entire array and capture in a hash table -> O(n)\n 2. OrderyBy: O(nlogn). Ordering inside each group also takes O(log) but all the interal list elements constitute the original array so that\'s another O(nlogn) \n 3. Total: O(nlogn) \n \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int[] FrequencySort(int[] nums) =>\n nums.GroupBy(v => v)\n .OrderBy(g => g.Count()).ThenByDescending(g => g.Key)\n .SelectMany(g => g).ToArray();\n}\n```
5
0
['C#']
1
sort-array-by-increasing-frequency
EASY AND EFFICIENT SOLUTION C++
easy-and-efficient-solution-c-by-king_of-rkbg
Intuition\n Describe your first thoughts on how to solve this problem. \nEasy C++ Solution Using Lambda Function and Hash Table.\n# Approach\n Describe your app
King_of_Kings101
NORMAL
2023-10-06T21:50:39.931280+00:00
2023-10-06T21:50:39.931297+00:00
823
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEasy C++ Solution Using Lambda Function and Hash Table.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n // USING LAMBDA FUNCTION\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> mp;\n\n for(int i = 0 ; i < nums.size() ; i++)\n mp[nums[i]]++;\n\n sort(nums.begin(), nums.end(),\n [&] (int a , int b){return mp[a]!=mp[b] ? mp[a] < mp[b] : a > b;});\n\n return nums;\n }\n};\n```
5
0
['Hash Table', 'Sorting', 'C++']
1
sort-array-by-increasing-frequency
C++ using Map || With Explanation...
c-using-map-with-explanation-by-sagarkes-y5tt
\nclass Solution {\npublic:\n static bool comp(pair<int,int>p,pair<int,int>q)\n //first column stores frequency i.e duplicates and second column stores va
sagarkesharwnnni
NORMAL
2022-08-04T20:14:47.051234+00:00
2022-08-04T20:14:47.051265+00:00
2,003
false
```\nclass Solution {\npublic:\n static bool comp(pair<int,int>p,pair<int,int>q)\n //first column stores frequency i.e duplicates and second column stores value\n {//if the duplicates are equal then we will return by greater value first...\n if(p.first==q.first)\n {\n return p.second>q.second;\n }\n ///else we will return as per frequency.\n return p.first<q.first;\n }\n vector<int> frequencySort(vector<int>& nums) {\n \n map<int,int>sk; \n for(int i=0;i<nums.size();i++){ ///inserting value and its duplicate in map...\n sk[nums[i]]++; \n }\n vector<int>ans;\n vector<pair<int,int>>temp; //creating pair so that we can sort\n for(auto i:sk){\n temp.push_back({i.second,i.first}); ///now adding duplicate in first and value in second column...\n }\n sort(temp.begin(),temp.end(),comp); ///sorting by function...\n for(auto z:temp){\n int a=z.first;\n int b=z.second;\n for(int j=0;j<a;j++){\n ans.push_back(b);\n }\n }\n \n return ans;\n }\n};\n```
5
0
['C']
0
sort-array-by-increasing-frequency
[JavaScript] Easy to understand - detailed explanation with map or array
javascript-easy-to-understand-detailed-e-1ozm
Core Strategy\n\nThe purpose of this problem is to sort the array with custom rules. It\'s straightforward, but we need to do more:\n- we need to count the freq
poppinlp
NORMAL
2022-03-07T04:42:36.564432+00:00
2022-03-07T04:51:07.614859+00:00
980
false
## Core Strategy\n\nThe purpose of this problem is to sort the array with custom rules. It\'s straightforward, but we need to do more:\n- we need to count the frequency first since we don\'t have it\n- we need to do the sorting with frequency and value\n\nFor the first step, we coud use a map or an array to do the counting.\nFor the second step, we could use JS native `sort` method for an array to do custom sorting.\n\n## Using a map\n\nFor this solution, we use a map to do the frequency counting. It\'s straightforward.\n\nHere\'s a sample code from me:\n\n```js\nconst frequencySort = (nums) => {\n const freq = {};\n for (const num of nums) {\n freq[num] = (freq[num] || 0) + 1;\n }\n return nums.sort((a, b) => freq[a] === freq[b] ? b - a : freq[a] - freq[b]);\n};\n```\n\n## Using an array and some tricks\n\nFor this solution, since the range of `num[i]` is small, so we could use a fixed-length array to do the counting. Take care of that `OFFSET` since the index of array should be non-negative.\n\nHere\'s a sample code from me:\n\n```js\nconst frequencySort = (nums) => {\n const freq = new Uint8Array(201);\n const OFFSET = 100;\n for (const num of nums) {\n ++freq[num + OFFSET];\n }\n return nums.sort((a, b, a2 = a + OFFSET, b2 = b + OFFSET) => freq[a2] === freq[b2] ? b - a : freq[a2] - freq[b2]);\n};\n```\n
5
0
['JavaScript']
1
sort-array-by-increasing-frequency
[C++] Priority Queue + Map | Comments for Easy Understanding 📌
c-priority-queue-map-comments-for-easy-u-9u03
Before you see this solution, I would highly suggest you to try this below problem :\n\uD83D\uDC49 https://leetcode.com/problems/top-k-frequent-elements/\n\nIf
yourdankfella
NORMAL
2021-07-21T08:28:57.571326+00:00
2022-02-27T09:39:26.362554+00:00
494
false
**Before you see this solution, I would highly suggest you to try this below problem :**\n\uD83D\uDC49 ***https://leetcode.com/problems/top-k-frequent-elements/***\n\n**If you solved the above problem, that\'s great. You can try again this problem and if still can\'t, then continue seeing this solution.** \n**In case you couldn\'t solve above link problem, see the below link solution and then see this solution, everything will become crystal-clear to you.**\n\uD83D\uDC49 ***https://leetcode.com/problems/top-k-frequent-elements/discuss/1352094/c-8ms-9932-faster-priority-queue-comments-for-easy-understanding***\n\n\n\n![image](https://assets.leetcode.com/users/images/f6bf1b3b-bc3c-4f0f-9c59-a2690006eaa5_1626855499.9966238.png)\n\n```\nclass Solution {\npublic:\n class compare_fun\n { \n public:\n // Since as you can see we have to sort decreasing order if frequency of two elements\n // is same, so we need *Custom Comparator Function* which is this \uD83D\uDC47\n bool operator()(pair<int, int> p1, pair<int, int> p2) \n { \n if(p1.first==p2.first)\n return p1.second < p2.second;\n return p1.first > p2.first;\n }\n };\n \n vector<int> frequencySort(vector<int>& nums) {\n \n //Creating map of array elements with their count\n unordered_map<int, int> mp;\n for(auto x: nums)\n mp[x]++;\n \n // *Min Heap*\n priority_queue<pair<int,int>, vector<pair<int,int>>, compare_fun> minH;\n vector<int> v;\n \n //Traversing through map and pushing it in heap\n for(auto x: mp){\n minH.push(make_pair(x.second, x.first)); // Making pair of count and the number\n }\n \n //Pushing the heap elements in vector multiplied with it\'s frequency\n while(minH.size() > 0){\n for(int i=0; i<minH.top().first; i++)\n v.push_back(minH.top().second);\n minH.pop();\n }\n \n return v;\n }\n};\n```
5
0
['Heap (Priority Queue)']
1
sort-array-by-increasing-frequency
Java Solution with MinHeap and HashMap
java-solution-with-minheap-and-hashmap-b-j0yf
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n int sortedArr[] = new int[nums.l
lord_voldemort
NORMAL
2021-04-05T17:23:36.767013+00:00
2021-04-05T17:23:36.767044+00:00
372
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n int sortedArr[] = new int[nums.length];\n for(int num: nums) {\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n Queue<Integer> minHeap = new PriorityQueue<Integer>((a,b)-> (map.get(a) == map.get(b)) ? b-a: map.get(a)-map.get(b) );\n for(int num: nums) {\n minHeap.add(num);\n }\n int i=0;\n while(!minHeap.isEmpty()) {\n sortedArr[i++] = minHeap.remove();\n }\n \n return sortedArr;\n }\n}\n```
5
0
[]
1
sort-array-by-increasing-frequency
C++ Solution
c-solution-by-vwo50-ah44
\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> counter;\n \n for (const auto& nu
vwo50
NORMAL
2021-03-05T03:42:02.451420+00:00
2021-03-05T03:42:02.451464+00:00
689
false
```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> counter;\n \n for (const auto& num : nums) counter[num]++; \n \n sort(nums.begin(), nums.end(), [&](int a, int b) {\n return counter[a] < counter[b] || (counter[a] == counter[b] && b < a);\n });\n \n return nums;\n }\n};\n```
5
1
['C']
1
sort-array-by-increasing-frequency
[Java] Solution using custom Sort
java-solution-using-custom-sort-by-vinsi-grzm
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int i : nums)\n
vinsinin
NORMAL
2021-03-04T03:52:59.482943+00:00
2021-03-04T03:52:59.482988+00:00
999
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int i : nums)\n map.put(i, map.getOrDefault(i,0) + 1);\n List<Map.Entry<Integer, Integer>> list = new ArrayList(map.entrySet());\n Collections.sort(list, (a,b) -> a.getValue() == b.getValue() ? b.getKey() - a.getKey() : a.getValue() - b.getValue());\n int j = 0;\n int[] res = new int[nums.length];\n for (Map.Entry<Integer, Integer> entry : list) \n for (int i=0; i<entry.getValue(); i++) res[j++] = entry.getKey();\n return res;\n }\n}\n```
5
0
['Java']
2
sort-array-by-increasing-frequency
Go Solution
go-solution-by-0xedb-ywlp
go\nfunc frequencySort(nums []int) []int {\n seen := map[int]int{}\n\n\tfor _, v := range nums {\n\t\tseen[v]++\n\t}\n\n sort.Slice(nums, func(i, j int) b
0xedb
NORMAL
2020-11-12T21:55:14.592565+00:00
2020-11-12T21:55:14.592592+00:00
348
false
```go\nfunc frequencySort(nums []int) []int {\n seen := map[int]int{}\n\n\tfor _, v := range nums {\n\t\tseen[v]++\n\t}\n\n sort.Slice(nums, func(i, j int) bool{\n if seen[nums[i]] == seen[nums[j]] {\n return nums[j] < nums[i]\n }\n \n return seen[nums[i]] < seen[nums[j]]\n })\n\n\treturn nums\n}\n \n```
5
0
['Go']
0
sort-array-by-increasing-frequency
[Java] Sort using custom (frequency) comparator
java-sort-using-custom-frequency-compara-pw1q
Calculate the occurence of each number and store it in a hashmap\n2. Define a custom comparator to sort first based on frequency and then based on value\n3. Fil
shyampandya
NORMAL
2020-10-31T16:09:21.075119+00:00
2020-10-31T16:09:21.075147+00:00
1,166
false
1. Calculate the occurence of each number and store it in a hashmap\n2. Define a custom comparator to sort first based on frequency and then based on value\n3. Fill into the result array\n\n```\npublic int[] frequencySort(int[] nums) {\n Map<Integer, Integer> freqCount = new HashMap();\n for (int n : nums) {\n freqCount.put(n, freqCount.getOrDefault(n, 0) + 1);\n }\n Comparator<Map.Entry<Integer, Integer>> valueComparator = new Comparator<Map.Entry<Integer, Integer>>() {\n @Override\n public int compare(Map.Entry<Integer, Integer> e1, Map.Entry<Integer, Integer> e2) {\n return e1.getValue() == e2.getValue() ? (e1.getKey() < e2.getKey() ? 1 : -1) : (e1.getValue() < e2.getValue() ? -1 : 1);\n }\n };\n \n List<Map.Entry<Integer, Integer>> sortedList = new ArrayList<Map.Entry<Integer, Integer>>(freqCount.entrySet());\n Collections.sort(sortedList, valueComparator);\n int[] result = new int[nums.length];\n int i = 0;\n for (Map.Entry<Integer, Integer> e : sortedList) {\n for (int j = 0; j < e.getValue(); ++j) {\n result[i++] = e.getKey();\n }\n }\n return result;\n }\n```
5
1
['Java']
0
sort-array-by-increasing-frequency
Easy to understand || Sorting || Mapping
easy-to-understand-sorting-mapping-by-ji-c3bz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
jitenagarwal20
NORMAL
2024-07-26T16:45:43.917176+00:00
2024-07-26T16:45:43.917218+00:00
39
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool mycompare(const pair<int,int> &lhs,const pair<int,int> &rhs){\n if(lhs.first != rhs.first)\n return lhs.first < rhs.first;\n return lhs.second > rhs.second;\n }\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int,int> mp;\n vector<pair<int,int>> v;\n\n for(auto it:nums)\n mp[it]++;\n\n for(auto it:mp)\n v.push_back({it.second,it.first});\n \n sort(v.begin(),v.end(),[](const pair<int,int> &lhs,const pair<int,int> &rhs){\n if(lhs.first != rhs.first)\n return lhs.first < rhs.first;\n return lhs.second > rhs.second;\n });\n vector<int> ans;\n for(auto it:v){\n while(it.first){\n ans.push_back(it.second);\n it.first--;\n }\n }\n return ans;\n }\n};\n```
4
0
['C++']
0
sort-array-by-increasing-frequency
Programmatic Approach || Implementation through Frequency Array ||
programmatic-approach-implementation-thr-58v9
Intuition\nChecking the Constraints you have -100 <= nums[i] <= 100 values which sums upto 201. It gives me an idea of using a frequency Array rather than a STL
KSR-68
NORMAL
2024-07-23T07:56:40.625157+00:00
2024-07-23T07:56:40.625182+00:00
557
false
# Intuition\nChecking the Constraints you have `-100 <= nums[i] <= 100` values which sums upto 201. It gives me an idea of using a frequency Array rather than a `STL <MAP>`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFrequency Array stores numbers in sorted order which reduces the time complexity used by a `STL <MAP>` data structures. <br>\nBut to store negative numbers we have to tweak some constraints.\n\nConstraints when storing the frequencies are:\n1. `if(nums[i] < 0)` then store between `1 <= i <= 100` index by `abs(i)`\n2. `if(nums[i] > 0)` store between `101 <= i <= 200` index by `100 + i`\n3. `if(nums[i] == 0)` store at `i = 0` {Corner Case}.\n\nBy using above approach you can easily fetch a frequency in O(1) constant time. \n\nNow we have to store the numbers with corresponding frequencies in an Data Structure so that we can make a `result` array.\n\nSo I ran a constant time loop from `0 to 200` and ignored the frequencies which are `0` and checked constraints accordingly.\n1. `if(i == 0)` then push the frequency of zero if exist. {Corner Case which is handled in above line t[i] == 0 }\n2. `1 <= i <= 100` then the `num` is negative then it should be inversed before pushing.\n3. `101 <=i <= 200` then the `num` is positive and it should be normalized by `100 - i` before pushing.\n\nThe LeetCode solution is Changing the input array inplace. \n\n# Complexity\n- Time complexity: O(N logN) for the `sort` function used\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(N) for the `freq` pairs\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n static bool compare(pair<int,int>& a, pair<int,int>& b){\n if(a.second == b.second) return a.first > b.first;\n return a.second < b.second;\n }\n vector<int> frequencySort(vector<int>& nums) {\n int n = nums.size();\n int t[201];\n memset(t, 0, sizeof(t));\n for(int i = 0; i<n; i++){\n if(nums[i] == 0) t[0]++;\n \n if(nums[i] < 0){\n t[abs(nums[i])]++;\n }\n else if(nums[i] > 0){\n t[100 + nums[i]]++;\n }\n }\n vector<pair<int,int>> freq;\n \n for(int i = 0; i<=200; i++){\n \n if(t[i] == 0) continue;\n \n if(i == 0) freq.push_back({0, t[i]});\n \n if(t[i] > 0 && i <= 100 && i > 0){\n freq.push_back({-i, t[i]});\n }\n \n else if (i > 100){\n freq.push_back({i - 100, t[i]});\n }\n }\n sort(freq.begin(), freq.end(), compare);\n\n vector<int> result;\n for(auto& [num, fr]: freq){\n while(fr--){\n result.emplace_back(num);\n }\n }\n return result;\n }\n};\n```
4
0
['Array', 'Sorting', 'C++']
0
sort-array-by-increasing-frequency
Easy Hash Table Sorting solution | Full Explaination
easy-hash-table-sorting-solution-full-ex-ejmz
Intuition\nThe problem requires us to sort an array of integers based on their frequency of occurrence. If two numbers have the same frequency, they should be s
jaitaneja333
NORMAL
2024-07-23T07:45:42.443787+00:00
2024-07-23T12:34:40.378648+00:00
434
false
# Intuition\nThe problem requires us to sort an array of integers based on their frequency of occurrence. If two numbers have the same frequency, they should be sorted by their values in descending order.\n\n# To achieve this:\n\nCount Frequencies: First, we need to determine how often each number appears in the array.\nSort by Frequency and Value: Then, we need to sort the array such that elements with lower frequencies come first. For elements with the same frequency, sort them in descending order of their values.\n\n# Approach\n\n1. Frequency Counting:\n\n=> Use an unordered_map (hash map) to store the frequency of each integer in the array. This allows us to efficiently count the occurrences of each integer.\n\n=>Traverse the array once to populate the hash map, where the key is the integer and the value is its frequency.\n\n2. Custom Sorting:\n\n=> Use the std::sort function with a custom comparator to sort the array based on the frequencies stored in the hash map.\n=> The comparator function compares two elements, a and b:\nIf their frequencies are equal, sort by value in descending order.\nOtherwise, sort by frequency in ascending order.\n=> This ensures that elements with lower frequencies appear first, and among those with the same frequency, larger values come before smaller values.\n3. Return the Sorted Array:\n\n=> After sorting, return the array with elements ordered according to the specified criteria.\n\n# Complexity\n- Time complexity: O(nlogn)\n- Frequency Counting: The frequency count operation takesO(n) time, where n is the number of elements in the array.\n- Sorting: The sorting step takes O(nlogn) time. This is the dominant factor in the time complexity, as the sort operation is based on the comparison of elements.\n- Overall Time Complexity: The total time complexity is O(nlogn), dominated by the sorting step.\n\n- Space complexity: O(n)\n- Frequency Map: Storing the frequency of each number requires O(n) additional space, as we need to keep track of the frequency for each unique number in the array.\n- Sorting: The space used for sorting is O(1) if we consider the space required by the sorting algorithm itself.\n- Overall Space Complexity: The total space complexity is O(n), primarily due to the hash map used to store frequencies\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n vector<int> frequencySort(std::vector<int>& nums) {\n std::unordered_map<int, int> hmap;\n\n for (int num : nums) {\n hmap[num]++;\n }\n\n // Sort the nums vector with a custom comparator\n sort(nums.begin(), nums.end(), [&](int a, int b) {\n if (hmap[a] == hmap[b]) {\n return a > b; // If frequencies are equal, sort by value in descending order\n }\n return hmap[a] < hmap[b]; // Otherwise, sort by frequency in ascending order\n });\n\n return nums;\n }\n};\n```\n![Shinchan_upvote.jpg](https://assets.leetcode.com/users/images/a0636988-c2e9-4fbe-acb0-1be6639a2b6d_1721720731.3337893.jpeg)\n\n
4
0
['Array', 'Hash Table', 'Sorting', 'C++']
0
sort-array-by-increasing-frequency
Beats 100% || Explained with Intuition and Diagram || 0ms
beats-100-explained-with-intuition-and-d-kul1
Intuition\n Describe your first thoughts on how to solve this problem. \nGiven the constraints -100 <= nums[i] <= 100, you can count the frequency of elements u
atharvf14t
NORMAL
2024-07-23T05:59:32.936886+00:00
2024-07-23T05:59:32.936919+00:00
1,349
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven 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.\n\nA similar concept can be applied using the Counter class in Python for a one-liner solution, which is slower but acceptable.\n\nAnother approach involves using counting sort, which reduces the time complexity to O(n + m).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount 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]; }.\n\nThe 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.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\nCounting sort: O(n+m)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m) where m=max(nums)\n\n# Code\n```\nclass Solution {\npublic:\n using int2=array<int,2>;\n vector<int> frequencySort(vector<int>& nums) {\n int n=nums.size(), freq[201]={0};\n for(int x:nums){\n freq[x+100]++;\n }\n \n sort(nums.begin(), nums.end(), [&](int x, int y){\n return (freq[x+100]==freq[y+100])?x>y:freq[x+100]<freq[y+100];\n });\n return nums;\n }\n};\n\n\n\n\n```
4
0
['C++']
2
sort-array-by-increasing-frequency
Sort Frequency to Number Mapping As Per Prolem Statement | Java | C++ | [Video Solution]
sort-frequency-to-number-mapping-as-per-fejtb
Intuition, approach, and complexity discussed in video solution in detail\n\n# Code\nJava\n\nclass Solution {\n public int[] frequencySort(int[] nums) {\n
Lazy_Potato_
NORMAL
2024-07-23T04:40:44.311900+00:00
2024-07-23T04:40:44.311936+00:00
730
false
# Intuition, approach, and complexity discussed in video solution in detail\n\n# Code\nJava\n```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer, Integer> numFreqMp = new HashMap<>();\n for(var num : nums){\n numFreqMp.put(num, numFreqMp.getOrDefault(num, 0)+1);\n }\n int mappingSize = numFreqMp.size();\n int freqNum[][] = new int[mappingSize][2];\n int indx = 0;\n for(var entry : numFreqMp.entrySet()){\n freqNum[indx++] = new int[]{entry.getValue(), entry.getKey()};\n }\n Arrays.sort(freqNum, (a, b)->{\n if(a[0] != b[0]){\n return a[0] - b[0];\n }else return b[1] - a[1];\n });\n List<Integer> res = new ArrayList<>();\n for(var pair : freqNum){\n int freq = pair[0], num = pair[1];\n while(freq-->0){\n res.add(num);\n }\n } \n return res.stream().mapToInt(Integer::intValue).toArray();\n }\n}\n```\nC++\n```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map<int, int> numFreqMp;\n for (int num : nums) {\n numFreqMp[num]++;\n }\n\n vector<pair<int, int>> freqNum;\n for (const auto& entry : numFreqMp) {\n freqNum.push_back({entry.second, entry.first});\n }\n\n sort(freqNum.begin(), freqNum.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n if (a.first != b.first) {\n return a.first < b.first;\n } else {\n return a.second > b.second;\n }\n });\n\n vector<int> res;\n for (const auto& pair : freqNum) {\n int freq = pair.first, num = pair.second;\n while (freq-- > 0) {\n res.push_back(num);\n }\n }\n return res;\n }\n};\n\n```
4
1
['Array', 'Hash Table', 'Sorting', 'C++', 'Java']
3
sort-array-by-increasing-frequency
🔥🔥 Explicación y Resolución Del Ejercicio En Español Java | Python | PHP | JavaScript | C++ 🔥🔥
explicacion-y-resolucion-del-ejercicio-e-9po8
Lectura\n1636 Sort Array by Increasing Frequency\n\nDado un arreglo de enteros, hay que ordenarlo en orden creciente seg\xFAn la frecuencia de los valores. \nSi
hermescoder02
NORMAL
2024-07-23T03:34:00.979097+00:00
2024-07-23T03:42:05.522967+00:00
244
false
# Lectura\n1636 Sort Array by Increasing Frequency\n\nDado un arreglo de enteros, hay que ordenarlo en orden creciente seg\xFAn la frecuencia de los valores. \nSi dichos valores tienen la misma frecuencia, ord\xE9nelos en orden decreciente.\n\nEntrada: nums = [2,3,1,3,2]\nSalida: [1,3,3,2,2]\n\nExplicaci\xF3n: \'2\' y \'3\' tienen una frecuencia de 2, por lo que est\xE1n ordenados en orden decreciente.\n\n\n# Video\n\nhttps://youtu.be/uC1VJbMwXGY\n\nSi te gust\xF3 el contenido \xA1te invito a suscribirte!: \n\u2705https://www.youtube.com/@hermescoder?sub_confirmation=1\n\n\u2705 Informaci\xF3n sobre clases particulares de algoritmos y programaci\xF3n:\nhttps://www.instagram.com/p/CxvsUwYOzFx/\n\n# Pasos para realizar el algoritmo:\n\n**1.-** Creamos un HashMap para almacenar las frecuencias. Recorremos el arreglo nums y agregamos un nuevo elemento, que tiene como clave el n\xFAmero evaluado y al valor se le va sumando uno.\n\n**2.-** Recorremos el hashmap de frecuencias y creamos una lista llamada response para almacenar tuplas que contienen el valor y su frecuencia correspondiente.\n\n**3.-** Ordenamos la lista de tuplas por frecuencia y luego por elemento, en este caso, utilizamos el Collections.sort\n\n**4.-** Creamos un nuevo arreglo para almacenar el resultado ordenado. Recorremos response, y por cada elemento, lo agregamos a result\n\n**5.-** Retornamos el resultado\n\n# C\xF3digo \n\n```Java []\n/*\n\n1636. Sort Array by Increasing Frequency\n\nDado un arreglo de enteros, hay que ordenarlo en orden creciente seg\xFAn la frecuencia de los valores. \nSi dichos valores tienen la misma frecuencia, ord\xE9nelos en orden decreciente.\n\nEntrada: nums = [2,3,1,3,2]\nSalida: [1,3,3,2,2]\n\nExplicaci\xF3n: \'2\' y \'3\' tienen una frecuencia de 2, por lo que est\xE1n ordenados en orden decreciente.\n */\n\n\nclass Solution {\n public int[] frequencySort(int[] nums) {\n // paso#1: \n //Creamos un HashMap para almacenar las frecuencias\n //Recorremos el arreglo nums y agregamos un nuevo elemento, que tiene como clave el n\xFAmero evaluado y al valor se le va sumando uno.\n HashMap<Integer, Integer> frecuencias = new HashMap<>();\n for (int num : nums) frecuencias.put(num, frecuencias.getOrDefault(num, 0) + 1);\n //frecuencias = {1=1, 2=2, 3=2}\n\n // paso#2\n // Recorremos el hashmap de frecuencias y creamos una lista llamada response para almacenar tuplas que contienen el valor y su frecuencia correspondiente.\n List<Integer[]> response = new ArrayList<>();\n for (Map.Entry<Integer, Integer> entry : frecuencias.entrySet()) response.add(new Integer[]{entry.getKey(), entry.getValue()});\n /*response =[\n val freq\n 1 1\n 2 2\n 3 2\n ]*/\n\n // paso#3\n // Ordenamos la lista de tuplas por frecuencia y luego por elemento, en este caso, utilizamos el Collections.sort\n Collections.sort(response, (a, b) -> {\n if (a[1] == b[1]) return b[0] - a[0]; // Ordenar elementos con la misma frecuencia en orden descendente\n else return a[1] - b[1]; // Ordenar por frecuencia en orden ascendente\n });\n /*response =[\n val freq\n 1 1\n 3 2\n 2 2 \n ]*/\n\n //Paso#4\n //Creamos un nuevo arreglo para almacenar el resultado ordenado. Recorremos response, y por cada elemento, lo agregamos a result.\n int[] result = new int[nums.length];\n int index = 0;\n for (Integer[] tupla : response) {\n int val = tupla[0];\n int freq = tupla[1];\n for (int i = 0; i < freq; i++) result[index++] = val;\n }\n\n //result = [1,3,3,2,2]\n\n\n\n //paso#5\n //Retornamos el resultado\n return result;\n\n\n }\n}\n```\n\n```PHP []\nclass Solution {\n function frequencySort($nums) {\n\n // asort($nums);\n $response = array();\n\n foreach ($nums as $key => $value) $response[$value]++;\n \n asort($response);\n\n $new_response=array();\n foreach ($response as $key => $value){\n\n $freq = $value;\n\n if(!isset($new_response[$freq]))$new_response[$freq]=array();\n \n for ($i = 0; $i < $freq; $i++) array_push($new_response[$freq], $key);\n\n rsort($new_response[$freq]);\n \n }\n \n $new_response2= array();\n foreach ($new_response as $key => $value){\n\n foreach ($value as $key2 => $value2){\n array_push($new_response2,$value2);\n }\n\n }\n\n return $new_response2;\n \n \n }\n}\n\n```\n\n```Python []\nclass Solution(object):\n def frequencySort(self, nums):\n frecuencias = {}\n for num in nums:\n frecuencias[num] = frecuencias.get(num, 0) + 1\n\n # Paso 2: Crear una lista de tuplas con valor y frecuencia\n respuesta = []\n for clave, valor in frecuencias.items():\n respuesta.append((valor, clave))\n\n # Paso 3: Ordenar la lista de tuplas por frecuencia y valor\n respuesta.sort(key=lambda x: (x[0], -x[1]))\n\n # Paso 4: Crear un nuevo array para almacenar el resultado ordenado\n resultado = [None] * len(nums)\n indice = 0\n for valor, clave in respuesta:\n for i in range(valor):\n resultado[indice] = clave\n indice += 1\n\n # Paso 5: Retornar el resultado\n return resultado\n\n```\n```JavaScript []\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar frequencySort = function(nums) {\n // Paso 1: Crear un objeto HashMap para almacenar las frecuencias\n const frecuencias = {};\n for (const num of nums) {\n frecuencias[num] = frecuencias[num] ? frecuencias[num] + 1 : 1;\n }\n // frecuencias = {1: 1, 2: 2, 3: 2}\n\n // Paso 2: Crear una lista para almacenar tuplas (valor, frecuencia)\n const response = [];\n for (const [key, value] of Object.entries(frecuencias)) {\n response.push([key, value]);\n }\n /* response = [\n [1, 1],\n [2, 2],\n [3, 2]\n ] */\n\n // Paso 3: Ordenar la lista por frecuencia y luego por valor\n response.sort((a, b) => {\n if (a[1] === b[1]) return b[0] - a[0]; // Ordenar elementos con la misma frecuencia en orden descendente\n else return a[1] - b[1]; // Ordenar por frecuencia en orden ascendente\n });\n /* response = [\n [1, 1],\n [3, 2],\n [2, 2]\n ] */\n\n // Paso 4: Crear un nuevo arreglo para almacenar el resultado ordenado\n const result = new Array(nums.length);\n let index = 0;\n for (const [value, freq] of response) {\n for (let i = 0; i < freq; i++) {\n result[index++] = value;\n }\n }\n\n // Paso 5: Retornar el resultado\n return result;\n};\n```\n\n```C++ []\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n // paso 1: Crear un mapa para almacenar las frecuencias\n map<int, int> frecuencias;\n for (int num : nums) {\n frecuencias[num]++;\n }\n\n // paso 2: Crear una lista de tuplas para almacenar el valor y su frecuencia\n vector<vector<int>> response;\n for (auto par : frecuencias) {\n response.push_back({par.first, par.second});\n }\n\n // paso 3: Ordenar la lista de tuplas por frecuencia y luego por valor\n sort(response.begin(), response.end(), [](const vector<int>& a, const vector<int>& b) {\n if (a[1] == b[1]) {\n return a[0] > b[0]; // Ordenar elementos con la misma frecuencia en orden descendente\n } else {\n return a[1] < b[1]; // Ordenar por frecuencia en orden ascendente\n }\n });\n\n // paso 4: Crear un nuevo vector para almacenar el resultado ordenado\n vector<int> result(nums.size());\n int index = 0;\n for (const vector<int>& tupla : response) {\n int valor = tupla[0];\n int frecuencia = tupla[1];\n for (int i = 0; i < frecuencia; i++) {\n result[index++] = valor;\n }\n }\n\n // paso 5: Retornar el resultado\n return result;\n }\n};\n```\n\n
4
0
['Array', 'Hash Table', 'PHP', 'Sorting', 'Python', 'C++', 'Java', 'JavaScript']
0
sort-array-by-increasing-frequency
using HashMap || PriorityQueue || beats 98% ||
using-hashmap-priorityqueue-beats-98-by-15r1y
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
tausif_02
NORMAL
2023-04-19T07:54:25.416869+00:00
2023-04-19T07:54:25.416899+00:00
481
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```\nclass Solution {\n class Pair\n {\n int num;\n int freq;\n Pair(int num, int freq)\n {\n this.num=num;\n this.freq=freq;\n }\n }\n public int[] frequencySort(int[] nums) {\n HashMap<Integer, Integer>h=new HashMap<>();\n for(int i=0;i<nums.length;i++){\n h.put(nums[i],h.getOrDefault(nums[i],0)+1);\n }\n PriorityQueue<Pair>pq=new PriorityQueue<>((a,b)->a.freq==b.freq?b.num-a.num: a.freq-b.freq);\n for(int i: h.keySet()){\n pq.add(new Pair(i, h.get(i)));\n }\n int arr[]=new int[nums.length];\n int j=0;\n while(!pq.isEmpty()){\n int n=pq.peek().num;\n int f=pq.peek().freq;\n pq.poll();\n for(int i=0; i<f; i++){\n arr[j]=n;\n j++;\n }\n }\n return arr; \n \n }\n}\n```
4
0
['Heap (Priority Queue)', 'Java']
0
sort-array-by-increasing-frequency
Java | Efficient | 1 ms | PriorityQueue | HashMap
java-efficient-1-ms-priorityqueue-hashma-cl1w
\n# Complexity\n- Time complexity:\nO ( n )\n\n- Space complexity:\nO ( n )\n\n# Code\n\nclass Solution {\n class Pair{\n int num;\n int freq;\
Aditi_sinha123
NORMAL
2022-12-30T17:23:02.965867+00:00
2022-12-30T17:23:02.965932+00:00
2,615
false
\n# Complexity\n- Time complexity:\nO ( n )\n\n- Space complexity:\nO ( n )\n\n# Code\n```\nclass Solution {\n class Pair{\n int num;\n int freq;\n Pair(int num, int freq){\n this.num=num;\n this.freq=freq;\n }\n }\n public int[] frequencySort(int[] nums) {\n HashMap<Integer, Integer>h=new HashMap<>();\n for(int i=0; i<nums.length; i++){\n h.put(nums[i], h.getOrDefault(nums[i],0)+1);\n }\n PriorityQueue<Pair>pq=new PriorityQueue<>((a,b)->a.freq==b.freq?b.num-a.num: a.freq-b.freq);\n for(int i: h.keySet()){\n pq.add(new Pair(i, h.get(i)));\n }\n int arr[]=new int[nums.length];\n int j=0;\n while(!pq.isEmpty()){\n int n=pq.peek().num;\n int f=pq.peek().freq;\n pq.poll();\n for(int i=0; i<f; i++){\n arr[j]=n;\n j++;\n }\n }\n return arr;\n }\n}\n```
4
0
['Hash Table', 'Heap (Priority Queue)', 'Java']
2
sort-array-by-increasing-frequency
Solution by using Priority Queue and Comparator in C++✅✅
solution-by-using-priority-queue-and-com-a9qe
\n\n\n#define pii pair<int, int>\n\nclass MyComp\n{\npublic:\n bool operator()(pii const &p1, pii p2)\n {\n if (p1.first == p2.first)\n {\n
shubhz_07
NORMAL
2022-12-03T07:03:41.153147+00:00
2022-12-03T07:03:41.153202+00:00
538
false
\n```\n\n#define pii pair<int, int>\n\nclass MyComp\n{\npublic:\n bool operator()(pii const &p1, pii p2)\n {\n if (p1.first == p2.first)\n {\n return p1.second <p2.second;\n }\n return p1.first >p2.first;\n }\n};\n\nclass Solution\n{\npublic:\n vector<int> frequencySort(vector<int> &nums)\n {\n vector<int> ans;\n priority_queue<pii, vector<pii>, MyComp> pq;\n\n unordered_map<int, int> mp;\n for (int n : nums)\n mp[n]++;\n\n for (auto it : mp)\n pq.push({it.second, it.first});\n\n while (not pq.empty())\n {\n int freq = pq.top().first;\n int n = pq.top().second;\n\n pq.pop();\n while (freq--)\n {\n ans.push_back(n);\n }\n }\n\n return ans;\n }\n};\n```
4
0
['C']
2
sort-array-by-increasing-frequency
Java | TreeMap | ArrayList | Sorting | Easy Solution
java-treemap-arraylist-sorting-easy-solu-jb2b
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer,Integer> map1 = new TreeMap<>();\n for(int i: nums)\n ma
Divyansh__26
NORMAL
2022-09-13T05:10:03.016740+00:00
2022-09-13T05:10:03.016780+00:00
1,476
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n Map<Integer,Integer> map1 = new TreeMap<>();\n for(int i: nums)\n map1.put(i,map1.getOrDefault(i,0)+1);\n Map<Integer,List<Integer>> map2 = new TreeMap<>();\n for(Map.Entry m: map1.entrySet()){\n int num = (int)m.getKey();\n int fre = (int)m.getValue();\n if(map2.containsKey(fre)){\n List<Integer> l = new ArrayList<>(map2.get(fre));\n l.add(num);\n map2.replace(fre,l);\n }\n else{\n List<Integer> l = new ArrayList<>();\n l.add(num);\n map2.put(fre,l);\n }\n }\n int arr[] = new int[nums.length];\n int index=0;\n for(Map.Entry m: map2.entrySet()){\n int fre = (int)m.getKey();\n List<Integer> l = new ArrayList<>(map2.get(fre));\n Collections.sort(l);\n for(int i=l.size()-1;i>=0;i--){\n for(int k=0;k<fre;k++){\n arr[index]=l.get(i);\n index++;\n }\n }\n }\n return arr;\n }\n}\n```\nKindly upvote if you like the code.
4
0
['Array', 'Tree', 'Sorting', 'Java']
0
sort-array-by-increasing-frequency
Simple Java Solution Using HashMap and Comparator
simple-java-solution-using-hashmap-and-c-dcnd
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n HashMap<Integer,Integer> hm=new HashMap<>(); //Creating frequency map\n for(int
harsh7578
NORMAL
2022-08-06T06:53:27.067015+00:00
2022-08-06T06:53:27.067054+00:00
696
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n HashMap<Integer,Integer> hm=new HashMap<>(); //Creating frequency map\n for(int x : nums)\n {\n if(hm.containsKey(x))\n {\n hm.put(x,hm.get(x)+1);\n }\n else\n {\n hm.put(x,1);\n }\n }\n Integer arr[]=new Integer[nums.length]; //since comparator cant be applied to primitive types\n for(int i=0;i<nums.length;i++)\n {\n arr[i]=nums[i]; //boxing\n }\n Arrays.sort(arr,new Comparator<Integer> ()\n {\n @Override\n public int compare(Integer a , Integer b)\n {\n if(hm.get(a)> hm.get(b))\n return 1;\n else if(hm.get(a)<hm.get(b))\n return -1;\n else\n return b-a;\n }\n });\n for(int i=0;i<nums.length;i++)\n {\n nums[i]=arr[i]; //unboxing\n }\n return nums;\n }\n}\n```\n\n**Please Upvote If It Helps**\n**Happy Coding : )**
4
0
['Java']
1
sort-array-by-increasing-frequency
Java Self Explanatory Easy To Understand 98% Faster
java-self-explanatory-easy-to-understand-x1e4
\nclass Solution {\n public int[] frequencySort(int[] nums) {\n HashMap<Integer,Integer> map = new HashMap<>();\n for(int i:nums) map.put(i,map
bharat194
NORMAL
2022-03-05T19:30:29.206921+00:00
2022-03-05T19:30:56.393958+00:00
1,403
false
```\nclass Solution {\n public int[] frequencySort(int[] nums) {\n HashMap<Integer,Integer> map = new HashMap<>();\n for(int i:nums) map.put(i,map.getOrDefault(i,0)+1);\n int[][] arr = new int[map.size()][2];\n int idx=0;\n for(int i:map.keySet()){\n arr[idx][0] = i;\n arr[idx++][1] = map.get(i);\n } \n Arrays.sort(arr,(i,j) -> {if(i[1] > j[1]) return 1; if(i[1] < j[1]) return -1; if(i[0] > j[0]) return -1;return 1;});\n idx=0;\n for(int i=0;i<arr.length;i++){\n while(arr[i][1]-->0) nums[idx++] = arr[i][0];\n }\n return nums;\n }\n}\n```
4
0
['Java']
0
sort-array-by-increasing-frequency
Easy and Explained C++ code | lambda expression
easy-and-explained-c-code-lambda-express-llhj
\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map <int,int> mp;\n // we need to modify our sort func
drv_rawt19
NORMAL
2022-02-20T11:23:45.506489+00:00
2022-02-20T11:23:45.506521+00:00
426
false
```\nclass Solution {\npublic:\n vector<int> frequencySort(vector<int>& nums) {\n unordered_map <int,int> mp;\n // we need to modify our sort function to do that we\'ll use \n // lambda fnction\n for(auto x: nums) mp[x]++;\n\t\t// [&](int a , int b) -> syntax of lambda exp. takes two input as we compare two values AND also use refrence as in our case ,need to acces mp (hashmap).\n sort(nums.begin(),nums.end(),[&](int a , int b){\n return mp[a]!=mp[b]?mp[a]<mp[b] : a>b;\n // mp[a]<mp[b] --> it. corresponds to lesser frequncy \n // a>b --> this to whose value is greater as said in que. store in dec.\n });\n return nums;\n }\n \n};\n```
4
0
['Array', 'C']
1
sort-array-by-increasing-frequency
Javascript Solution
javascript-solution-by-mbournehalley-uufr
\n/**\n * Time Complexity: O(nlogn)\n * Space Complexity: O(n)\n * @param {number[]} nums\n * @return {number[]}\n */\nconst frequencySort = function (nums) {
mbournehalley
NORMAL
2021-11-19T04:01:16.739539+00:00
2021-11-19T04:03:40.354662+00:00
776
false
```\n/**\n * Time Complexity: O(nlogn)\n * Space Complexity: O(n)\n * @param {number[]} nums\n * @return {number[]}\n */\nconst frequencySort = function (nums) { \n return nums.sort(compareFrequency(mapFrequency(nums)));\n};\n\n/**\n * @param {number[]} nums\n * @return {number{}}\n */\nconst mapFrequency = function (nums) {\n return nums.reduce(\n (acc, cur) => (acc[cur] = (acc[cur] || 0) + 1, acc)\n , {}); \n}\n\n/**\n * @param {number{}} frequency\n * @return {number}\n */\nconst compareFrequency = function (frequency) {\n return function (a, b) {\n return (frequency[a] - frequency[b]) || b - a;\n }\n}\n\n```
4
0
['JavaScript']
2
sort-array-by-increasing-frequency
EZ Python Code For Beginners O(NLogN)
ez-python-code-for-beginners-onlogn-by-s-y8uf
\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n d={}\n nums.sort()\n nums=nums[::-1]\n for i in nums
SaumyaRai29
NORMAL
2021-10-26T09:42:28.666712+00:00
2021-10-26T09:42:28.666759+00:00
498
false
```\nclass Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n d={}\n nums.sort()\n nums=nums[::-1]\n for i in nums:\n if i not in d:\n d[i]=0\n d[i]+=1\n ans=[]\n d=dict(sorted(d.items(),key=lambda x:x[1]))\n for i,j in d.items():\n while d[i]!=0:\n ans.append(i)\n d[i]-=1\n return ans\n```
4
0
['Sorting', 'Python']
1
sort-array-by-increasing-frequency
Typescript | Clean and simple solution
typescript-clean-and-simple-solution-by-hbm23
\nfunction frequencySort(nums: number[]): number[] {\n \n const freq: Record<number, number> = {};\n \n nums.forEach(num => freq[num] = (freq[num] |
mihirbhende1201
NORMAL
2021-09-26T06:22:40.276795+00:00
2021-09-26T06:22:40.276850+00:00
264
false
```\nfunction frequencySort(nums: number[]): number[] {\n \n const freq: Record<number, number> = {};\n \n nums.forEach(num => freq[num] = (freq[num] || 0) + 1);\n\n return nums.sort((a, b) => freq[a] != freq[b] ? freq[a] - freq[b] : b - a);\n};\n```
4
0
['TypeScript', 'JavaScript']
1