Sort Characters By Frequency - Leetcode 451 - Python

  Рет қаралды 20,203

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 53
@satyamjha68
@satyamjha68 11 ай бұрын
Solved it!! It has become my daily routine now . First thing I do after waking up is solving daily challenge. Even during college exams I follow this rigorously !!
@sagaciousjunebug
@sagaciousjunebug 11 ай бұрын
How long do you spend on a problem and what do you do when a problem is too difficult?
@satyamjha68
@satyamjha68 11 ай бұрын
@@sagaciousjunebug Even I don't have definite answer for this. I still ask the same question with many people. I give the problem an hour then I see some hints . If I am still unable to solve it after another half hour , I look at the solution and add it to a list of revision question! Generally Hard with less than 60% acceptance rate is currently where I am facing issue.
@nicolasguillenc
@nicolasguillenc 11 ай бұрын
you have become one of my favorite youtubers in the last month, thank you so much
@leeroymlg4692
@leeroymlg4692 11 ай бұрын
in this specific problem, I believe it's more efficient to add the frequencies to a list and sort it. Because if you iterate through the range of s length, s can be as long as 5 * 10^5. meanwhile there can only be 52 different frequencies due to there only being 52 unique characters in the input. So sorting a list of 52 elements would be quicker
@sriramchitta7400
@sriramchitta7400 11 ай бұрын
exactly what i am thinking
@cannonkalra
@cannonkalra 11 ай бұрын
62*
@anon_y_mousse
@anon_y_mousse 11 ай бұрын
I've done something similar to this in C. I wrote a simple jumble solver to check my answers, and even generated an alternate dictionary file where the words were sorted and followed by the unsorted matches. Which also made it easy to just grep for all the possible matches if I sorted the letters myself first. I find that C is significantly easier to use for string handling than Python.
@ecchioni
@ecchioni 11 ай бұрын
The difference between "adding" to a string and using a join is actually huge. My C# solution went from 1600ms to 64ms when I changed to StringBuilder. I used a PQ though to sort the counts.
@kapilkhandelwal48
@kapilkhandelwal48 11 ай бұрын
I also thought of a priority queue to sorting this in terms of count then push it into the answer
@AdrianCuet
@AdrianCuet 11 ай бұрын
yeah in my case it went from 200ms to 50ms aprox, but had to recode what i ve done
@varunpalsingh3822
@varunpalsingh3822 11 ай бұрын
I solved this myself, all thanks to you navdeep😄
@ranjeet_sohanpal
@ranjeet_sohanpal 9 ай бұрын
what? I didn't know that this dude is Punjabi
@MP-ny3ep
@MP-ny3ep 11 ай бұрын
Thank you for the daily leetcode problems. It helps a lot. Another great explanation as always!
@davi_singh
@davi_singh 11 ай бұрын
solved this using a hashmap and a heapq in python, needed to modify the priority a bit by multiplying by -1 to get the max num everytime but it worked :)
@yaswanthkosuru
@yaswanthkosuru 11 ай бұрын
You can reverse the result after using minheap itself
@davi_singh
@davi_singh 11 ай бұрын
@@yaswanthkosuru yup though reversing would be an O(n) operation right? Multiplying by -1 felt like a quicker way, though I could be wrong
@32gigs96
@32gigs96 11 ай бұрын
(f ^^ g) x = (f x, g x) f = concatMap (uncurry replicate) . sortBy (flip compare) . map (length ^^ head) . group . sortBy (flip compare) just a quick one liner that took a minute. Could use a Map for better perf ofc but couldn't be bothered as i was in the repl lol
@thiagosdev
@thiagosdev 11 ай бұрын
Well, i did this: from queue import PriorityQueue class Solution: def frequencySort(self, s: str) -> str: count = {} for c in s: count[c] = count.get(c, 0) + 1 pq = PriorityQueue() for c, f in count.items(): pq.put((-f, c)) res = "" while not pq.empty(): f, c = pq.get() res += c * -f return res
@trueArcticFox
@trueArcticFox 11 ай бұрын
First -Thanks for detailed step-by-step solution! Second - Perhaps it will be useful for someone to see a one-line solution: return ''.join(i*j for i,j in sorted(Counter(s).items(), reverse=True, key=lambda x: x[1]))
@vans4lyf2013
@vans4lyf2013 11 ай бұрын
Why is bucket sort O(n) instead of n^2? The second for loop is nested and can’t buckets have n items so shouldn’t that be n^2?
@ayaanahmad1085
@ayaanahmad1085 7 күн бұрын
In the worst case it should run O(n*2) times with this unless we have a check to prevent the loop running when the number of characters added to final string are > length of the string. So even if there is a string like "aaaaa". It will stop after first iteration since all characters are printed
@Lost1nTranslation
@Lost1nTranslation 11 ай бұрын
Thanks for uploading these
@dumbpandabear7947
@dumbpandabear7947 11 ай бұрын
Why is this solution slower than nlogn solutions that sort by frequency or use a priority queue if this i O(n)?
@m.kamalali
@m.kamalali 11 ай бұрын
We have Counter of max size (low and upper case English letters) so sort is o(1) , and uses single dictionary (Counter) which if faster than using two(Counter &freq)
@Marcox385
@Marcox385 11 ай бұрын
Just got my first 5% in both runtime and memory usage lmao I'm getting worse by the day
@TacticalDoge101
@TacticalDoge101 11 ай бұрын
IMO those stats are pretty inaccurate. If I submit the same solution twice, I would get 2 different scores, and the difference would be huge. So don't worry about the percentage, be happy that you were able to solve a problem on your own ;) If you can think of an optimal solution, great, if not, take a look at the hints.
@barnetthan9391
@barnetthan9391 11 ай бұрын
Are you concatenating strings instead of using something like stringbuilder? That would slow you down a lot
@achan3073
@achan3073 8 ай бұрын
this is basically same as top K frequent elements
@hirakhirak9119
@hirakhirak9119 11 ай бұрын
i am new to leetcoding, what would be the difficulty level of this question?
@user-gh2gw8cx2b
@user-gh2gw8cx2b 11 ай бұрын
Like medium. It's a good example of bucket sort .
@chrischika7026
@chrischika7026 11 ай бұрын
easy medium@@user-gh2gw8cx2b
@levelup2014
@levelup2014 11 ай бұрын
Why are most of these question in python does he do problems using JavaScript?
@georgeg.9696
@georgeg.9696 11 ай бұрын
I don't think that bucket sort is the bets answer here. It will have a space cost of O(n) and time O(n), where n is the len of s. Computing the frequences and sorting it will not exactly be O(nlogn) because the number of valid characters is at most 62, so we can say that sorting the frequences will be a constant time operation, so the time complexity will be only the time complexity of counting the chars frequency O(n)
@ecchioni
@ecchioni 11 ай бұрын
Technically the upper char limit is 2^16.
@akshayiithyd
@akshayiithyd 11 ай бұрын
Even I did what you did. However both the solutions will have same big O time complexity. For bucket sort approach, there will be only as many distinct counts in worst case, as the number of distinct letters, which cant be greater than 62, hence evern that is O(1) space
@georgeg.9696
@georgeg.9696 11 ай бұрын
@@ecchioni in this problem is only upper case, lower case english letters and digits
@ecchioni
@ecchioni 11 ай бұрын
@@georgeg.9696 Here yes, but the hard upper limit is UTF-16.
@shubh9207
@shubh9207 11 ай бұрын
Can someone please explain me how the bucket is storing int values in Ascending order? Is it the counter function which stores most frequent values first or what is it?
@shubh9207
@shubh9207 11 ай бұрын
No shiz I realized that we're iterating through each and every possible length in the last loop, damn so clever.
@Garensonic
@Garensonic 3 ай бұрын
If the interviewer asked that the same frequency characters were sorted alphabetically would there be a way to address that in Python
@rajsuriyang3427
@rajsuriyang3427 11 ай бұрын
nlogn solution runs faster in leetcode. WTF is happening?
@maxpapirovnyk
@maxpapirovnyk 6 ай бұрын
Thanks for explanation! in your solution we can move the multiply part to the buckets generation: buckets[cnt].append(char * cnt)
@iamstudying389
@iamstudying389 3 ай бұрын
tc: 0(n) and sc: o(128) i.e. constant in cpp string frequencySort(string s) { string ans; int arr[128]={0} ; for(int i = 0 ; i0) { ans+= char(index); maxi--; } if(ans.size()==s.size()) break; } return ans; }
@ninjaasmoke
@ninjaasmoke 11 ай бұрын
past few days seem to be easy questions
@memeproductions4182
@memeproductions4182 11 ай бұрын
Time complexity for sorting is not n log n since you sort the characters and their are 62 worst case, so that's O(62 log 62)
@owlmostdead9492
@owlmostdead9492 11 ай бұрын
That’s medium?
@chrischika7026
@chrischika7026 11 ай бұрын
yup but I would say easy medium
@ibrahimalshubaily9520
@ibrahimalshubaily9520 11 ай бұрын
monthly subscription for courses pls
@hundred_gaming123
@hundred_gaming123 11 ай бұрын
class Solution: def frequencySort(self, s: str) -> str: k = "" d = Counter(s) d = { k :v fork, v in sorted(d.items(),key = operator.itemgetter(1))} //sort by val in dict for val in d: k += val * d[val] return k[::-1]
@shantanushukla1082
@shantanushukla1082 7 ай бұрын
Such a bad explanation
Largest Divisible Subset - Leetcode 368 - Python
22:57
NeetCodeIO
Рет қаралды 16 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 783 М.
Their Boat Engine Fell Off
0:13
Newsflare
Рет қаралды 15 МЛН
Counter-Strike 2 - Новый кс. Cтарый я
13:10
Marmok
Рет қаралды 2,8 МЛН
8 Data Structures Every Programmer Should Know
17:09
ForrestKnight
Рет қаралды 243 М.
I made Tetris in C, this is what I learned
15:15
Austin Larsen
Рет қаралды 28 М.
Microservices are Technical Debt
31:59
NeetCodeIO
Рет қаралды 735 М.
I Solved 100 LeetCode Problems
13:11
Green Code
Рет қаралды 310 М.
How I Mastered Data Structures and Algorithms in 8 Weeks
15:46
Aman Manazir
Рет қаралды 157 М.
I Solved 1583 Leetcode Questions  Here's What I Learned
20:37
ThePrimeTime
Рет қаралды 786 М.
Minimize XOR - Leetcode 2429 - Python
12:17
NeetCodeIO
Рет қаралды 6 М.
The LeetCode Fallacy
6:08
NeetCode
Рет қаралды 600 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 490 М.
Their Boat Engine Fell Off
0:13
Newsflare
Рет қаралды 15 МЛН