Top K Frequent Words - Priority Queue Approach (LeetCode)

  Рет қаралды 36,346

AlgosWithMichael

AlgosWithMichael

Күн бұрын

Пікірлер: 77
@jacquelinepassehl425
@jacquelinepassehl425 3 жыл бұрын
This video was amazing and really helped me in preparing for technical interviews! thank you so much for this, you just got a new subscriber :D
@AlgosWithMichael
@AlgosWithMichael 2 жыл бұрын
Thank you for the support!
@Metachief_X
@Metachief_X 2 жыл бұрын
Hey bro, god bless you. i was struggling with this problem for a couple hours.... studying hard for my next interviews... you rock! keep making videos :)
@darthvader_
@darthvader_ 3 жыл бұрын
Michael, you are a savior! I happened to solve this question earlier but the explanation you gave helped a lot!
@CostaKazistov
@CostaKazistov 2 жыл бұрын
Nice walkthrough and the solution. Here is Kotlin version: class Solution { fun topKFrequent(words: Array, k: Int): List { val result = mutableListOf() val comparator = Comparator { a, b -> if (a.value != b.value) b.value.compareTo(a.value) else a.key.compareTo(b.key) } val queue = PriorityQueue(comparator) words.groupingBy { it }.eachCount().forEach { queue.offer(it) } while (result.size < k && queue.isNotEmpty()) result.add(queue.poll().key) return result } }
@snowy-ur9qq
@snowy-ur9qq Жыл бұрын
Thanks for the clear explanation! I have a follow-up question about time complexity - since each of the n entries in the map is added to the queue (and polled only if the queue size exceeds k), shouldn't the time complexity be O(n*logn)?
@animatedzombie64
@animatedzombie64 3 жыл бұрын
N time for map insertion, Nlogk for actual heap insertion because it heapifies on every insertion, and finally Klogk for reversing the list. so N + Nlogk + Klogk => NlogK upperbound.
@Bubdiddly
@Bubdiddly 2 жыл бұрын
Thank you this is what I was wondering
@manojrajasekar6035
@manojrajasekar6035 4 жыл бұрын
Fantastic one Michael. Keep doin more :)
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Definitely, thank you for watching!
@silverbullet_6
@silverbullet_6 3 жыл бұрын
Thanks bro i Almost forgot about the @override method.❤️
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
No problem 👍
@amberlala2163
@amberlala2163 4 жыл бұрын
I think that using lambda expression to initialize the priority queue is more concise. ^-^
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Very true, I just didn't want to use that way in case people had not seen lambda syntax before.
@z41n70
@z41n70 3 жыл бұрын
For those wondering how to do the lamba version: PriorityQueue pq = new PriorityQueue((a, b)->map.get(a)-map.get(b)==0?b.compareTo(a):map.get(a)-map.get(b));
@KanagaveluSugumar
@KanagaveluSugumar 2 жыл бұрын
I dont think we need to reverse it. Need to change word1.compareTo(word2) ? By the way your videos are more helpful. Thank you!
@manjunathbhadrannavar5165
@manjunathbhadrannavar5165 2 ай бұрын
My que is, why use a priority queue? because we just need to return top k from a map of key value pairs, sort using a custom comparator and return top k values, simple 🤷‍♂
@GochiCity
@GochiCity Жыл бұрын
So the reason we create a min heap for getting MAX k values is to reduce the amount of elements we store in the heap. If we do a max heap then we will continue to keep storing values we are not going to use. Interesting
@KCML036
@KCML036 2 жыл бұрын
how come we don't take comparing the string lexicographically part into the Big O? Wouldn't that be worst case length of the maximum string. Say max string length is m then wouldn't the big O be n*(m*logk)
@sofiayz7472
@sofiayz7472 3 жыл бұрын
I know it's going to be a very dumb question but why frequency1-frequency2?
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Not a dumb question at all! It is because we need to sort the lesser frequencies first. So for example, lets say frequency1 is 2 and frequency2 is 4, this would do 2 - 4 = -2. Since it is a negative number, we are saying word1 is less than word2 in sorted order.
@sofiayz7472
@sofiayz7472 3 жыл бұрын
@@AlgosWithMichael Thank you so much for your reply! You are absolutely a great teacher!I just subscribed to your channel and can't wait to learn more from you!
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
No problem! Thank you so much for watching my content, I really appreciate it 👍
@oven5997
@oven5997 2 жыл бұрын
Thanks for sharing, great explanation
@AlgosWithMichael
@AlgosWithMichael 2 жыл бұрын
My pleasure!
@franklinshih9169
@franklinshih9169 3 жыл бұрын
great explanation omg thank you
@wendycheng6856
@wendycheng6856 3 жыл бұрын
Great explanation! Pretty Clear!
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Glad it was helpful!
@AnuragBaidyanath
@AnuragBaidyanath 4 жыл бұрын
Great explanation michael!
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Glad it was helpful!
@VinodKumar-vd9ou
@VinodKumar-vd9ou 2 жыл бұрын
Bro, nice video but i think storing words in Map is not a good idea in case we have huge number of string files, Trie could be a better approach for efficient storage and also you can store counts at leaf node of trie.
@priyanshumohanty5261
@priyanshumohanty5261 Жыл бұрын
I think based on the constraints specified in the question, this sure is a good method. Besides, tries can be trickier
@tomladdus9264
@tomladdus9264 4 жыл бұрын
What would you do if your standard library does not have a Priority Queue? For example, Swift, if this is asked by Apple, does not have a PQ as part of the standard library. Would they expect you to write one on the spot?
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
I think what they would do is just say to assume you have a Priority Queue implementation already written
@ArghyaBhattacharyaNITA
@ArghyaBhattacharyaNITA 3 жыл бұрын
"Love isn't supposed to come before 'I" '. That my friend, is a heavy truth :)
@sumitrakumarishaw2885
@sumitrakumarishaw2885 3 жыл бұрын
Thanks from India
@indiansoftwareengineer4899
@indiansoftwareengineer4899 3 жыл бұрын
Thanks Michael.
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Thank you!
@sputnikone3724
@sputnikone3724 3 жыл бұрын
What is the purpose of using a minheap here? Why not use a maxheap instead and then pop the top K ones?
@chiragchandak9554
@chiragchandak9554 4 жыл бұрын
amazing work brother
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Thank you so much 😀
@Руслан-х7и2э
@Руслан-х7и2э Жыл бұрын
thank you man, i understand)
@codeduel
@codeduel 2 жыл бұрын
The last return of the Comparator isn’t safe. The code may give the wrong answer when there is overflow. For instance, when comparing a large negative value to a large positive value, the difference may be more than the largest value that can be stored in an integer, Integer.MAX_VALUE
@mohammadyahya78
@mohammadyahya78 2 жыл бұрын
Thank you very much. I still don't understand the comparator and why you said frq1-freq2 while word2.compareTo(word1) and not word1.compareTo(word2) please?
@SheikhSadiruddin1
@SheikhSadiruddin1 2 жыл бұрын
You want to remove the less frequent words and those that have greater alphabetical ordering.
@bz9031
@bz9031 4 жыл бұрын
Hi, I have a question. Why do we have to use map.Entry in this case? Could we simply use map.keySet()?
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
You could also use a keySet 😀
@BlumChoi
@BlumChoi Жыл бұрын
if k=1 and I have n unique strings, than the sorting suggested in the video will take O(nlog(n)), wouldn't it?
@codeduel
@codeduel Жыл бұрын
No. It will be O(n)
@christeenathomas6108
@christeenathomas6108 3 жыл бұрын
please solve this problem using python3
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Yea, if enough people want python instead of java I can do that
@venkataraman2716
@venkataraman2716 2 жыл бұрын
do you have python 3 code using same approach
@leomonz
@leomonz 4 жыл бұрын
Why can’t you do word1.compareTo(word2)?
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Because you only sort by the word strings if the frequencies are the same
@obaid5761
@obaid5761 4 жыл бұрын
@@AlgosWithMichael i think he meant why it's the other way around
@satheshbm92
@satheshbm92 4 жыл бұрын
Yes I have the same question. Why can't we use word1.compareTo(word2) in the comparator?
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Oh I see. You still can't flip them, you would get different results if you did word1.compareTo(word2). I just tried now and failed multiple test cases :/
@uvedkhan1
@uvedkhan1 4 жыл бұрын
@@AlgosWithMichael Thats the question, why is like that?
@woodylucas
@woodylucas 3 жыл бұрын
Is that comparator class similar to JavaScript sort method?
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Yes, I believe so
@jeffreylee911
@jeffreylee911 4 жыл бұрын
why don't we do this in correct order directly instead of reversing it in the end?
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
2 months late on this response lol sorry did not see it. The reason why is because when we insert into our priority queue, we are inserting the words in reverse alphabetical order, we want it in alphabetical order for the final result
@jeffreylee911
@jeffreylee911 3 жыл бұрын
@@AlgosWithMichael But still helpful! Thanks a lot!
@namisha6883
@namisha6883 3 жыл бұрын
@@AlgosWithMichael Why are we not counting complexity of reverse sorting in the end, which is O(N Log N) and certainly greater than O(N* log k)
@Alex7nt
@Alex7nt 3 жыл бұрын
@@namisha6883 reverse is not NlogN, you do N/2 operations to reverse cause u swap a[i] with a[length - i]. And since N/2 < NLOGK the timr complexity mantains in nlogk
@soulboy2223
@soulboy2223 3 жыл бұрын
perfect!
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
thanks!
@NguyenCuong-sg2kg
@NguyenCuong-sg2kg 3 жыл бұрын
How about use Trie
@AlgosWithMichael
@AlgosWithMichael 2 жыл бұрын
I'm not sure if a Trie would improve the complexity
@pramodsharma4508
@pramodsharma4508 3 жыл бұрын
The problem was asked at a google interview with input size of 1 trillion
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Oof Google be asking hard questions :p
@VadimFilin
@VadimFilin 2 жыл бұрын
Lol, implement PriorityQueue in C or Go at first. Dislike
Amazon Coding Interview Question - First Missing Positive (LeetCode)
20:47
Word Ladder | Breadth First Search (LeetCode)
15:08
AlgosWithMichael
Рет қаралды 13 М.
Worst flight ever
00:55
Adam W
Рет қаралды 40 МЛН
How do Cats Eat Watermelon? 🍉
00:21
One More
Рет қаралды 12 МЛН
Single-Threaded CPU - Priority Queue - Leetcode 1834 - Python
17:20
Top K Frequent Elements - Leetcode 347 - Heaps (Python)
14:08
Merge K Sorted Lists - Divide and Conquer Approach
12:01
AlgosWithMichael
Рет қаралды 18 М.
Minimum Window Substring | Sliding Window | LeetCode
18:00
AlgosWithMichael
Рет қаралды 39 М.
TOP K FREQUENT WORDS| LEETCODE 692 | PYTHON CUSTOM HEAP SOLUTION
13:38
Cracking FAANG
Рет қаралды 2,3 М.
Text Justification Algorithm (LeetCode)
30:45
AlgosWithMichael
Рет қаралды 31 М.
Amazon Coding Question - Insert Delete GetRandom O(1)
11:54
AlgosWithMichael
Рет қаралды 10 М.
WHY IS THE STACK SO FAST?
13:46
Core Dumped
Рет қаралды 158 М.
Decode String | FAANG Coding Question | Stack
17:03
AlgosWithMichael
Рет қаралды 10 М.
Worst flight ever
00:55
Adam W
Рет қаралды 40 МЛН