Top K Frequent Words - Priority Queue Approach (LeetCode)

  Рет қаралды 34,862

AlgosWithMichael

AlgosWithMichael

Күн бұрын

Here is a step by step explanation of a priority queue based question called Top K Frequent Words asked at many top tech companies!
Check out my interview prep platform for learning the patterns!
📢 Interview Prep Platform: algoswithmichael.com
🎧 Join the community Discord: / discord
💰 Support me on Patreon: / michaelmuinos
🔗Follow me on LinkedIn: / michael-muinos
📂Follow me on Github: github.com/MichaelMuinos

Пікірлер: 76
@darthvader_
@darthvader_ 3 жыл бұрын
Michael, you are a savior! I happened to solve this question earlier but the explanation you gave helped a lot!
@Metachief_X
@Metachief_X Жыл бұрын
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 :)
@jacquelinepassehl425
@jacquelinepassehl425 2 жыл бұрын
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!
@manojrajasekar6035
@manojrajasekar6035 4 жыл бұрын
Fantastic one Michael. Keep doin more :)
@AlgosWithMichael
@AlgosWithMichael 4 жыл бұрын
Definitely, thank you for watching!
@franklinshih9169
@franklinshih9169 3 жыл бұрын
great explanation omg thank you
@CostaKazistov
@CostaKazistov Жыл бұрын
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 } }
@wendycheng6856
@wendycheng6856 3 жыл бұрын
Great explanation! Pretty Clear!
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Glad it was helpful!
@user-cl2db4uo5d
@user-cl2db4uo5d 9 ай бұрын
thank you man, i understand)
@AnuragBaidyanath
@AnuragBaidyanath 3 жыл бұрын
Great explanation michael!
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Glad it was helpful!
@oven5997
@oven5997 2 жыл бұрын
Thanks for sharing, great explanation
@AlgosWithMichael
@AlgosWithMichael 2 жыл бұрын
My pleasure!
@silverbullet_17
@silverbullet_17 3 жыл бұрын
Thanks bro i Almost forgot about the @override method.❤️
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
No problem 👍
@snowy-ur9qq
@snowy-ur9qq 11 ай бұрын
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)?
@indiansoftwareengineer4899
@indiansoftwareengineer4899 3 жыл бұрын
Thanks Michael.
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Thank you!
@chiragchandak9554
@chiragchandak9554 3 жыл бұрын
amazing work brother
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Thank you so much 😀
@sumitrakumarishaw2885
@sumitrakumarishaw2885 2 жыл бұрын
Thanks from India
@animatedzombie64
@animatedzombie64 2 жыл бұрын
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
@soulboy2223
@soulboy2223 3 жыл бұрын
perfect!
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
thanks!
@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 2 жыл бұрын
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));
@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
@KCML036
@KCML036 Жыл бұрын
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)
@bz9031
@bz9031 3 жыл бұрын
Hi, I have a question. Why do we have to use map.Entry in this case? Could we simply use map.keySet()?
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
You could also use a keySet 😀
@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?
@venkataraman2716
@venkataraman2716 2 жыл бұрын
do you have python 3 code using same approach
@HarshySZN
@HarshySZN Жыл бұрын
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
@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?
@Ikhideifidon
@Ikhideifidon Жыл бұрын
No. It will be O(n)
@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 Жыл бұрын
You want to remove the less frequent words and those that have greater alphabetical ordering.
@VinodKumar-vd9ou
@VinodKumar-vd9ou Жыл бұрын
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
@woodylucas
@woodylucas 3 жыл бұрын
Is that comparator class similar to JavaScript sort method?
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
Yes, I believe so
@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 👍
@Ikhideifidon
@Ikhideifidon 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
@NguyenCuong-sg2kg
@NguyenCuong-sg2kg 2 жыл бұрын
How about use Trie
@AlgosWithMichael
@AlgosWithMichael 2 жыл бұрын
I'm not sure if a Trie would improve the complexity
@jeffreylee911
@jeffreylee911 3 жыл бұрын
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)
@alienwareCL
@alienwareCL 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
@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 3 жыл бұрын
Yes I have the same question. Why can't we use word1.compareTo(word2) in the comparator?
@AlgosWithMichael
@AlgosWithMichael 3 жыл бұрын
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 3 жыл бұрын
@@AlgosWithMichael Thats the question, why is like that?
@ArghyaBhattacharyaNITA
@ArghyaBhattacharyaNITA 3 жыл бұрын
"Love isn't supposed to come before 'I" '. That my friend, is a heavy truth :)
@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
@KanagaveluSugumar
@KanagaveluSugumar Жыл бұрын
I dont think we need to reverse it. Need to change word1.compareTo(word2) ? By the way your videos are more helpful. Thank you!
@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 Жыл бұрын
Lol, implement PriorityQueue in C or Go at first. Dislike
FAANG Coding Interview Question - Container With Most Water (LeetCode)
13:30
TOP K FREQUENT WORDS| LEETCODE 692 | PYTHON CUSTOM HEAP SOLUTION
13:38
Cracking FAANG
Рет қаралды 1,4 М.
Became invisible for one day!  #funny #wednesday #memes
00:25
Watch Me
Рет қаралды 20 МЛН
Вечный ДВИГАТЕЛЬ!⚙️ #shorts
00:27
Гараж 54
Рет қаралды 13 МЛН
1 or 2?🐄
00:12
Kan Andrey
Рет қаралды 30 МЛН
Amazon Coding Interview Question - First Missing Positive (LeetCode)
20:47
Word Ladder | Breadth First Search (LeetCode)
15:08
AlgosWithMichael
Рет қаралды 13 М.
Minimum Window Substring | Sliding Window | LeetCode
18:00
AlgosWithMichael
Рет қаралды 38 М.
Merge K Sorted Lists - Divide and Conquer Approach
12:01
AlgosWithMichael
Рет қаралды 17 М.
Coding Interview Question - Merge Two Sorted Lists (LeetCode)
8:57
AlgosWithMichael
Рет қаралды 5 М.
Kadane's Algorithm - Maximum Subarray (Dynamic Programming)
8:24
AlgosWithMichael
Рет қаралды 24 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 610 М.
Priority Queue Explained | Min and Max Heap | Custom Comparator
23:19
Daily Code Buffer
Рет қаралды 18 М.
Search in Rotated Sorted Array II - Leetcode 81 - Python
17:36
NeetCodeIO
Рет қаралды 12 М.
Урна с айфонами!
0:30
По ту сторону Гугла
Рет қаралды 8 МЛН
cute mini iphone
0:34
승비니 Seungbini
Рет қаралды 6 МЛН