No video

Kth Largest Element in a Stream - Leetcode 703 - Python

  Рет қаралды 126,249

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
💡 BINARY SEARCH PLAYLIST: • Binary Search
📚 STACK PLAYLIST: • Stack Problems
Problem Link: neetcode.io/problems/kth-larg...
0:00 - Read the problem
2:20 - Drawing Explanation
8:10 - Coding Explanation
leetcode 703
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#coding #interview #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 101
@jay-rathod-01
@jay-rathod-01 2 жыл бұрын
Definitely medium.
@juanpablomesalopez
@juanpablomesalopez 2 жыл бұрын
Hey thanks for the videos. Just wanted to add something. Instead of adding each new val to the heap and poping the smallest value each time, you could first check if val >= minHeap[0]. Which is a O(1) operation. If it is True, then push val to heap and pop minimum value. Otherwise just skip the push and pop operations.
@ObtecularPk
@ObtecularPk 2 жыл бұрын
That's a good optimization 👍
@abenezermelaku2882
@abenezermelaku2882 Жыл бұрын
raises index out of range error if our input is empty
@PeterPan-xe7qw
@PeterPan-xe7qw Жыл бұрын
@@abenezermelaku2882 7 months later lol, but you could check if minHeap and val >= minHeap[0] This would allow the proper check w/out out of bounds error
@laeekahmed2683
@laeekahmed2683 10 ай бұрын
if (len(self.minHeap) < self.k or val > self.minHeap[0]): heapq.heappush(self.minHeap, val)
@s0lomate
@s0lomate Күн бұрын
wasn't able to understand the question and had to see your video for it. But after it I was able to come up with the solution pretty quickly.
@fereshtehlux3412
@fereshtehlux3412 2 жыл бұрын
Thank you for the explanation. However, I want to mention that the time complexity is O(nlogk) not O(nlogn) since the size of heap is k then the depth and the number of operations to add a new value will be logk (not logn).
@leetcoderafeeq2641
@leetcoderafeeq2641 Жыл бұрын
For the constructor: Popping from a heap of size n is logn. Do that n-k times. If n is much greater than k, popping from the heap (originally of size n) until the heap has a size of k would be O(n*logn) Time. For the add method: O(M*logk) Time Now that the heap is size k, popping is logk.
@markolainovic
@markolainovic Жыл бұрын
@@leetcoderafeeq2641 What is M, though?
@pacomarmolejo3492
@pacomarmolejo3492 Жыл бұрын
@@markolainovic M are the number of calls to the add method
@pacomarmolejo3492
@pacomarmolejo3492 Жыл бұрын
if you are constantly resizing the heap (making sure it is of length k) in each iteration of the loop in the constructor it is indeed nlogk. However, in Neet's solution, size adjustment is done at the end, then nlogn.
@del6553
@del6553 Ай бұрын
@@pacomarmolejo3492 this exactly
@lennythach607
@lennythach607 2 жыл бұрын
Honestly, I didn't even understand what the question was even asking. spent 15min trying to understand it. lol, Thanks for the Explanation. Now that I understand I'll try to solve it before looking at any solution.
@dmaynard83
@dmaynard83 2 жыл бұрын
Love your content keep up the great work!
@harunguven8581
@harunguven8581 Жыл бұрын
Easy and beginner level heap questions were needed, thank you for adding. Very good explanations.
@jenso413
@jenso413 2 жыл бұрын
so in javascript there is no function to convert an array into a heap.. you have to do it by hand.. and this is supposed to be an easy problem LOL
@razisyed9481
@razisyed9481 Жыл бұрын
At 2:35, I think it's incorrect that it would take O(n) to find the kth largest element by scanning through the unsorted input. It would take O(n)^2 as you would have to compare each element to every other element and count how many elements are larger than the current element. You would get your answer once you find an element for which there are k-1 larger elements. This could take O(n)^2 in the worst case. And at 2:39, when the array is sorted, we don't need to use binary search. We can simply access the kth largest element at index n-k in O(1) time.
@ram-s-77
@ram-s-77 5 ай бұрын
This is exactly why I came to comments. I knew those 2 time complexities given are wrong. Thanks for the validation
@kklr1234
@kklr1234 2 жыл бұрын
Thanks for the great videos. Can you do a video on how you shoot the videos and what software/tools you use?
@HKabir360
@HKabir360 Жыл бұрын
Love your content. Thank you so much for your effort
@jorgechamorroguitar
@jorgechamorroguitar 2 жыл бұрын
Thanks a lot, great explanation
@loccc88
@loccc88 2 жыл бұрын
Hey NeetCode, I just began to watch your videos only very recently. And I can safely say it's the most helpful resource out there including all the paid ones. As for this question, can you explain why you decided to pop from minHeap in both the _init_ and the add() functions? I just popped in the add() and it worked just fine.
@animeshtiwary4110
@animeshtiwary4110 Жыл бұрын
it's because when you first instantiate the stream, the number of elements in the heap could be greater than k. so like [4,5,8,2,1] and k = 3. so before adding, we have to pop all the elements until it becomes size k -> [4,5,8]. now when we do the add operation (lets say we are adding 6, heap becomes [4,5,8,6] but we also have to return the kth largest in the add operation. but our heap is more than k elements, so we have to pop AGAIN in add to make it k elements, and then finally we can return the first element of the heap (smallest element of heap of size k)
@clintondannolfo714
@clintondannolfo714 2 жыл бұрын
Good solution but could be amortized constant time `add` operation if we checked the min value on the heap before pushing it
@rezwanurrahman7090
@rezwanurrahman7090 Жыл бұрын
Good point. It should be able to improve the runtime if the stream values are not monotonically increasing.
@kapil1024IT
@kapil1024IT 2 жыл бұрын
Can't we skep add if len >= k and val
@anthonyhsu3182
@anthonyhsu3182 Жыл бұрын
can i use the nlargest function in heapq python to initialize the length k heap instead of using while to pop extra element?
@ogoubah
@ogoubah 2 жыл бұрын
Hi Neetcode, please I'm stuck on the problem "Accounts Merge" LC 721 please could you do a video solution on it, thanks!
@kuzelnet
@kuzelnet 2 жыл бұрын
I was confused with the time complexity of heappop. Getting the min value in a heap is O(1), but pop is O(log n) (not O(1)!) because log n elements has to be reordered after the pop. Don't get confused with arrays!
@pauljones9150
@pauljones9150 2 жыл бұрын
What's the correct Time Complexity of the Add vs the __init__() then?
@nolanbrewer574
@nolanbrewer574 Жыл бұрын
Thank you!
@jointcc2
@jointcc2 Жыл бұрын
good reminder, thanks
@dhairyashiil
@dhairyashiil 2 жыл бұрын
Thank You !... , Your explanation made my day : )
@abhimalyachowdhury7835
@abhimalyachowdhury7835 2 жыл бұрын
Superb as always!
@hamsalekhavenkatesh3440
@hamsalekhavenkatesh3440 8 ай бұрын
Love this idea, another idea is to ise TreeMap where we store the element and its count...and we maintain its size to K... we add it to the treeMap only if min element is < newly added element. Still same time complexity but u r cautious not to add everytime into the treemap
@shekharchaurasiya5236
@shekharchaurasiya5236 Күн бұрын
Such a good explanation, thank you.
@n.h.son1902
@n.h.son1902 Ай бұрын
The constructor definitely helps us reduce the time complexity to O(logk)
@hmmm-ts3rb
@hmmm-ts3rb 2 жыл бұрын
awesome, thank you! can you do number of islands II? i'm so stuck on that one
@sathyanarayanankulasekaran5928
@sathyanarayanankulasekaran5928 2 жыл бұрын
u shud do a BFS...starting with 1 and mark visited as BFS is done.
@symbol767
@symbol767 2 жыл бұрын
Thanks man, liked
@kirillzlobin7135
@kirillzlobin7135 11 ай бұрын
4:26 Cannot understand If we are using mi heap, it means that in the beggining of the array we will have smaller values, how can we choose the largest ones among them?
@averysaltyburrito1192
@averysaltyburrito1192 3 ай бұрын
When we pop from the heap, how do we know that it is definitely the smallest element in the Heap? I.e. since a Heap only has a weak ordering, how is this guaranteed?
@oualidlaib5965
@oualidlaib5965 Жыл бұрын
Poping from the minimu value from the heap is O( log(n) ) not O( 1 )
@trantung2013
@trantung2013 2 жыл бұрын
For curiosity, could we use builtin funciton or we should implement a simpler version of min-heap in actual coding interview?
@apekplusplus
@apekplusplus 2 жыл бұрын
You’re allowed to directly use a built in heap in your preferred language. No need to implement it for a problem. Unless of course the problem is “implement a heap” :)
@Karan-gh9ki
@Karan-gh9ki 9 ай бұрын
@@apekplusplus or you are coding in javascript
@jiteshsharma3388
@jiteshsharma3388 6 ай бұрын
Hi, Can we use Priority Queue? Or we should use the approach which you have mentioned, it may impress interviewer.
@MrMukulpandey
@MrMukulpandey 2 жыл бұрын
to master this code....what topics should i have to learn?
@minciNashu
@minciNashu 2 жыл бұрын
heapq has two operations which do push and pop in one go, seemingly more efficient than separate calls heapq.heapreplace and heapq.heappushpop def add(self, val: int) -> int: # case 1: empty heap if len(self.nums) < self.k: heapq.heappush(self.nums, val) # case 2: k-sized heap, insert if value is higher than min; the check is optional, heapq also runs that check in the implementation elif val > self.nums[0]: heapq.heappushpop(self.nums, val) return self.nums[0]
@thmstbst
@thmstbst 2 жыл бұрын
Idk I did that, but the runtime was longer when I tried it your way. Super weird. You'd think a dedicated function would work at least as well
@abhishekrbhat8919
@abhishekrbhat8919 7 ай бұрын
great explanation
@asdfasyakitori8514
@asdfasyakitori8514 9 ай бұрын
Great video
@sabaamanollahi5901
@sabaamanollahi5901 2 жыл бұрын
Thank you so much for these contents, they are really helping! just that in 2:40 I think the complexity in the sorted one is O(1) since we just want to pick a special index!
@re-think7693
@re-think7693 Жыл бұрын
How will you know the index?
@eobardthawne6903
@eobardthawne6903 Жыл бұрын
We want to pick a special element and not Index bruh!
@user-hf8iy8xp9y
@user-hf8iy8xp9y 2 ай бұрын
shouldn't self.minHeap be initialized to nums[:] and not nums? that is, a copy of nums? in general, it's not a good idea to mutate the input provided. am i correct?
@amboojmittal2993
@amboojmittal2993 Жыл бұрын
can't we have count logic and we can do in O(n)?
@homyakMilashka
@homyakMilashka 9 ай бұрын
It's also worth mentioning that to find k largest number in a sorted array, you need constant time. Just take the kth element from the back of the array.
@kirillzlobin7135
@kirillzlobin7135 11 ай бұрын
But how. In the min heap 2 should be in the very beggining if we use 4, 5, 8, 2 values
@picklerick8123
@picklerick8123 7 ай бұрын
what if you were not allowed to use the built in heap structure? that would make this problem hard
@IK-xk7ex
@IK-xk7ex Жыл бұрын
Not all languages do have Heap in their std library. I expected to see the implemented heap on array
@pauljones9150
@pauljones9150 2 жыл бұрын
Just wanted to say I noticed that the self.k versus k usage is somewhat inconsistent. In some places, you use it, and in some areas, you don't. I don't know if this is a mistake or intentionally done. Either way, love your videos. Cheers,.
@mohamedhussien4013
@mohamedhussien4013 Жыл бұрын
Thanks.
@MP-ny3ep
@MP-ny3ep Жыл бұрын
Thank you for such an easy solution.
@s8x.
@s8x. 11 ай бұрын
heapq object comes in clutch
@emmanuelromero2258
@emmanuelromero2258 Жыл бұрын
What is the space complexity?
@jeremiahbenjamin5776
@jeremiahbenjamin5776 Жыл бұрын
O(n), where n is the size of array stored in the heap.
@zihuq9842
@zihuq9842 9 ай бұрын
I don't think this solution would pass at the higher levels of MAANG since using built-in helpers such as heapify disqualify you (happened to me during an interview at facebook a few years ago). They would want you to implement what heapify does from scratch, even if it's less efficient to do so in the langauge because they're rather see how you would go about doing so when you don't have built-ins to help you in your day-to-day work. Just food for thought.
@user-he4xf2yw4z
@user-he4xf2yw4z 9 ай бұрын
Lol
@IPatricio
@IPatricio 5 ай бұрын
Most interviewers don't care. I think you just had a bad interviewer. Would they also expect you to implement quick sort if you needed to sort a list?
@tranpaul4550
@tranpaul4550 4 ай бұрын
feel bad because of that interview mindset. Its like we dont want you to use Google to search for thing, use your own custom-code from scratch search Engine
@mayursonowal
@mayursonowal Жыл бұрын
How is pop not a O(1) operation?
@VivekGawande1
@VivekGawande1 Жыл бұрын
Because we need to find the new min once we remove the old min. We replace it with the rightmost and bottom most node in the heap and then bubble down.
@abhiseklimbu1475
@abhiseklimbu1475 Жыл бұрын
how does self.minHeap[0] return the k largest element? The root of the min-heap should return the smallest element
@Deescacha
@Deescacha Жыл бұрын
Put n elements in a min heap, with n>=k. Then pop elements from the heap until there are exactly k elements in the heap. What does the root point to?
@RandomShowerThoughts
@RandomShowerThoughts 4 ай бұрын
it's because we're essentially using the min heap to cut off anything lower than k. All values that are smaller than minheap[0] are dropped, it is the smallest element of the min heap but it will always be the kth largest element
@killerdwag
@killerdwag 5 ай бұрын
Using the built in python hep functions if cheating. knowing how to maintain the heap is the whole point of these questions
@jhonsen9842
@jhonsen9842 Жыл бұрын
Well they have changed this question from easy to medium.
@listentoalina
@listentoalina 9 ай бұрын
False
@accountutilitario7196
@accountutilitario7196 10 ай бұрын
🎯 Key Takeaways for quick navigation: 00:00 🎯 Introduction to Problem - Introduction to the problem of finding the kth largest element in a stream of numbers. - Explanation of the problem requirements, including the definition of "kth largest element in sorted order." 02:13 🤔 Problem Solving Approach - Discussion of the naive approach: sorting the input array, binary search, and its limitations. - Introduction of the optimal approach: using a min heap of size k to efficiently find the kth largest element in the stream. - Explanation of the advantages of using a min heap and the reasoning behind its implementation for this problem. 08:20 💻 Implementation in Python - Detailed walkthrough of the Python implementation of the problem solution. - Explanation of the constructor function, initializing the min heap, and ensuring its size is k. - Description of the add function, including how new elements are added to the min heap and maintaining its size. - Demonstrated the efficient time complexity of the implemented solution and the significance of using a min heap for this problem. Made with HARPA AI
@Cloud-577
@Cloud-577 2 жыл бұрын
what if we were asked to not use built in library
@rahulbera454
@rahulbera454 2 жыл бұрын
they won't
@Cloud-577
@Cloud-577 2 жыл бұрын
@@rahulbera454 thank you
@somnathroy102
@somnathroy102 9 ай бұрын
The problem is not explained properly in the question at the source. This was supposed to be easy.
@shalinisangal84
@shalinisangal84 2 ай бұрын
Explanation was medium and code part was easy
@Antinormanisto
@Antinormanisto Күн бұрын
I'm here because I don't understand description
@stylisgames
@stylisgames 13 күн бұрын
No love for JS which doesn't have a built-in heapify function, huh
@EranM
@EranM 4 ай бұрын
This question is NOT easy LOL!
@numberonep5404
@numberonep5404 2 жыл бұрын
a cute prb
@idontnowachannelname
@idontnowachannelname 2 жыл бұрын
good luck in google
@raz_dva_
@raz_dva_ Жыл бұрын
The problem is disliked because the way it is written is far from "Clear Explanation". Sometimes authors of Leetcode problems take very heavy drugs
@ynng
@ynng Жыл бұрын
heapq feels like cheating
@BikerInsights
@BikerInsights 22 сағат бұрын
anyone here for problem of the day???
@alexruan5639
@alexruan5639 2 жыл бұрын
This is pretty confusing.
@ninjaturtle205
@ninjaturtle205 Жыл бұрын
n elements in array min heap keeps the min element at the top if n = 100, heapify the original array. length of minheap is now 100 if you want the the 3rd largest element from the original array, then pop the heap 97 times. now new element arrives. add to heap. heap is now len 4. Pop once, now again you have the 3rd largest lement at the top of minheap
@creationuk8637
@creationuk8637 Жыл бұрын
@@ninjaturtle205 🔥🤩
@deepanshurohilla8188
@deepanshurohilla8188 2 жыл бұрын
C++ solution please
@fw4568
@fw4568 Күн бұрын
Who is here at August 12. 2024?
@user-hf8iy8xp9y
@user-hf8iy8xp9y 16 күн бұрын
shouldn't the constructor limit the heap size to k? creating a copy of nums and heapifying it would cost O(n log n), correct? in the constructor - we could add one integer at a time to the heap, and whenever the size of heap is bigger than k, we pop. code: ``` def __init__(self, k: int, nums: List[int]): # min heap with k largest integers self.min_heap = [] self.k = k for num in nums: heapq.heappush(self.min_heap, num) if len(self.min_heap) > k: heapq.heappop(self.min_heap) ``` thoughts?
Викторина от МАМЫ 🆘 | WICSUR #shorts
00:58
Бискас
Рет қаралды 6 МЛН
World’s Largest Jello Pool
01:00
Mark Rober
Рет қаралды 123 МЛН
Jumping off balcony pulls her tooth! 🫣🦷
01:00
Justin Flom
Рет қаралды 32 МЛН
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 166 М.
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 784 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 423 М.
This video will change your mind about the AI hype
17:07
NeetCode
Рет қаралды 661 М.
Why is everyone LYING?
7:56
NeetCodeIO
Рет қаралды 219 М.
Software engineer interns on their first day be like...
2:21
Frying Pan
Рет қаралды 13 МЛН
Levy Tournament Round 7 | !sale !tournament !delay
GothamChess
Рет қаралды 8 М.
Rotting Oranges - Leetcode 994 - Python
12:19
NeetCode
Рет қаралды 95 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 304 М.
5 Math Skills Every Programmer Needs
9:08
Sahil & Sarra
Рет қаралды 1 МЛН
Викторина от МАМЫ 🆘 | WICSUR #shorts
00:58
Бискас
Рет қаралды 6 МЛН