Kth Largest Element in a Stream - Leetcode 703 - Python

Поделиться
HTML-код
  • Опубликовано: 16 ноя 2024

Комментарии • 108

  • @juanpablomesalopez
    @juanpablomesalopez 2 года назад +81

    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 года назад +2

      That's a good optimization 👍

    • @abenezermelaku2882
      @abenezermelaku2882 2 года назад +5

      raises index out of range error if our input is empty

    • @PeterPan-xe7qw
      @PeterPan-xe7qw Год назад +3

      @@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 Год назад +3

      if (len(self.minHeap) < self.k or val > self.minHeap[0]):
      heapq.heappush(self.minHeap, val)

  • @fereshtehlux3412
    @fereshtehlux3412 2 года назад +67

    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 2 года назад +11

      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 2 года назад +2

      @@leetcoderafeeq2641 What is M, though?

    • @pacomarmolejo3492
      @pacomarmolejo3492 Год назад +1

      @@markolainovic M are the number of calls to the add method

    • @pacomarmolejo3492
      @pacomarmolejo3492 Год назад +6

      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 4 месяца назад +1

      @@pacomarmolejo3492 this exactly

  • @jay-rathod-01
    @jay-rathod-01 3 года назад +60

    Definitely medium.

  • @lennythach607
    @lennythach607 2 года назад +16

    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.

  • @razisyed9481
    @razisyed9481 Год назад +13

    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 8 месяцев назад +3

      This is exactly why I came to comments. I knew those 2 time complexities given are wrong. Thanks for the validation

    • @spiceybyte
      @spiceybyte 2 месяца назад +2

      Great correction thanks

    • @AustinCS
      @AustinCS 2 месяца назад

      Yea, when he said binary search i was tilting my entire head.

  • @ku-1119
    @ku-1119 2 года назад +7

    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 года назад +1

      What's the correct Time Complexity of the Add vs the __init__() then?

    • @nolanbrewer574
      @nolanbrewer574 Год назад

      Thank you!

    • @jointcc2
      @jointcc2 Год назад

      good reminder, thanks

  • @s0lomate
    @s0lomate 3 месяца назад +3

    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.

  • @clintondannolfo714
    @clintondannolfo714 2 года назад +5

    Good solution but could be amortized constant time `add` operation if we checked the min value on the heap before pushing it

    • @rezwanurrahman7090
      @rezwanurrahman7090 2 года назад +1

      Good point. It should be able to improve the runtime if the stream values are not monotonically increasing.

  • @dmaynard83
    @dmaynard83 3 года назад +12

    Love your content keep up the great work!

  • @Antinormanisto
    @Antinormanisto 3 месяца назад +6

    I'm here because I don't understand description

  • @jenso413
    @jenso413 2 года назад +12

    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

    • @monsvta
      @monsvta 2 месяца назад

      "For Priority Queue / Queue data structures, you may use 5.4.0 version of datastructures-js/priority-queue and 4.2.3 version of datastructures-js/queue."

    • @homeroserna9983
      @homeroserna9983 Месяц назад

      Imagine leetcoding in javascript

  • @minciNashu
    @minciNashu 2 года назад +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 года назад +1

      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

  • @dusvn1484
    @dusvn1484 Месяц назад

    I'm brutal fascinated how this problem is good and how this appoarch of thinking will grow my mind.
    I love you neet

  • @somnathroy102
    @somnathroy102 Год назад +1

    The problem is not explained properly in the question at the source. This was supposed to be easy.

  • @harunguven8581
    @harunguven8581 Год назад +1

    Easy and beginner level heap questions were needed, thank you for adding. Very good explanations.

  • @oualidlaib5965
    @oualidlaib5965 Год назад +2

    Poping from the minimu value from the heap is O( log(n) ) not O( 1 )

  • @kapil1024IT
    @kapil1024IT 2 года назад +3

    Can't we skep add if len >= k and val

  • @hamsalekhavenkatesh3440
    @hamsalekhavenkatesh3440 11 месяцев назад

    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

  • @n.h.son1902
    @n.h.son1902 5 месяцев назад

    The constructor definitely helps us reduce the time complexity to O(logk)

  • @loccc88
    @loccc88 2 года назад +4

    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 Год назад +4

      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)

  • @jorgechamorroguitar
    @jorgechamorroguitar 3 года назад +4

    Thanks a lot, great explanation

  • @homyakMilashka
    @homyakMilashka Год назад +1

    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.

  • @kklr1234
    @kklr1234 3 года назад +3

    Thanks for the great videos. Can you do a video on how you shoot the videos and what software/tools you use?

  • @sabaamanollahi5901
    @sabaamanollahi5901 2 года назад +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 2 года назад +2

      How will you know the index?

    • @eobardthawne6903
      @eobardthawne6903 Год назад

      We want to pick a special element and not Index bruh!

  • @shekharchaurasiya5236
    @shekharchaurasiya5236 3 месяца назад

    Such a good explanation, thank you.

  • @zihuq9842
    @zihuq9842 Год назад +1

    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.

    • @KostyaZinoview
      @KostyaZinoview Год назад

      Lol

    • @IPatricio
      @IPatricio 8 месяцев назад +2

      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 7 месяцев назад

      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

  • @HKabir360
    @HKabir360 2 года назад +1

    Love your content. Thank you so much for your effort

  • @jiteshsharma3388
    @jiteshsharma3388 9 месяцев назад

    Hi,
    Can we use Priority Queue?
    Or we should use the approach which you have mentioned, it may impress interviewer.

  • @MrMukulpandey
    @MrMukulpandey 2 года назад +2

    to master this code....what topics should i have to learn?

  • @trantung2013
    @trantung2013 2 года назад +3

    For curiosity, could we use builtin funciton or we should implement a simpler version of min-heap in actual coding interview?

    • @apekplusplus
      @apekplusplus 2 года назад +6

      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 Год назад

      @@apekplusplus or you are coding in javascript

  • @ogoubah
    @ogoubah 3 года назад +2

    Hi Neetcode, please I'm stuck on the problem "Accounts Merge" LC 721 please could you do a video solution on it, thanks!

  • @pauljones9150
    @pauljones9150 2 года назад +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,.

  • @averysaltyburrito1192
    @averysaltyburrito1192 6 месяцев назад

    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?

  • @abhishekrbhat8919
    @abhishekrbhat8919 10 месяцев назад

    great explanation

  • @IK-xk7ex
    @IK-xk7ex Год назад +2

    Not all languages do have Heap in their std library. I expected to see the implemented heap on array

  • @abhimalyachowdhury7835
    @abhimalyachowdhury7835 2 года назад

    Superb as always!

  • @kirillzlobin7135
    @kirillzlobin7135 Год назад

    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?

  • @dhairyashiil
    @dhairyashiil 2 года назад

    Thank You !... , Your explanation made my day : )

  • @anthonyhsu3182
    @anthonyhsu3182 2 года назад

    can i use the nlargest function in heapq python to initialize the length k heap instead of using while to pop extra element?

  • @AzimBaghadiya
    @AzimBaghadiya 5 месяцев назад

    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?

  • @hmmm-ts3rb
    @hmmm-ts3rb 3 года назад +1

    awesome, thank you! can you do number of islands II? i'm so stuck on that one

  • @asdfasyakitori8514
    @asdfasyakitori8514 Год назад

    Great video

  • @bushvatoi
    @bushvatoi 28 дней назад

    My O(logK) solution. Beats 100% in Python:
    class KthLargest:
    def __init__(self, k: int, nums: List[int]):
    self.k = k
    self.min_heap = []
    for num in nums:
    if len(self.min_heap) < k:
    heapq.heappush(self.min_heap, num)
    elif num > self.min_heap[0]:
    heapq.heapreplace(self.min_heap, num)
    def add(self, val: int) -> int:
    if len(self.min_heap) < self.k:
    heapq.heappush(self.min_heap, val)
    elif val > self.min_heap[0]:
    heapq.heapreplace(self.min_heap, val)
    return self.min_heap[0]

  • @picklerick8123
    @picklerick8123 10 месяцев назад

    what if you were not allowed to use the built in heap structure? that would make this problem hard

  • @killerdwag
    @killerdwag 8 месяцев назад

    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.

  • @MP-ny3ep
    @MP-ny3ep Год назад

    Thank you for such an easy solution.

  • @emmanuelromero2258
    @emmanuelromero2258 Год назад

    What is the space complexity?

  • @shalinisangal84
    @shalinisangal84 5 месяцев назад

    Explanation was medium and code part was easy

  • @maitreyakanitkar8742
    @maitreyakanitkar8742 Месяц назад

    this guy is so fucking smart.

  • @accountutilitario7196
    @accountutilitario7196 Год назад +1

    🎯 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

  • @kirillzlobin7135
    @kirillzlobin7135 Год назад

    But how. In the min heap 2 should be in the very beggining if we use 4, 5, 8, 2 values

  • @amboojmittal2993
    @amboojmittal2993 Год назад

    can't we have count logic and we can do in O(n)?

  • @s8x.
    @s8x. Год назад

    heapq object comes in clutch

  • @symbol767
    @symbol767 2 года назад

    Thanks man, liked

  • @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 Год назад +1

      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 7 месяцев назад

      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

  • @mohamedhussien4013
    @mohamedhussien4013 Год назад

    Thanks.

  • @stylisgames
    @stylisgames 3 месяца назад

    No love for JS which doesn't have a built-in heapify function, huh

  • @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.

  • @Cloud-577
    @Cloud-577 2 года назад

    what if we were asked to not use built in library

  • @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

  • @idontnowachannelname
    @idontnowachannelname 2 года назад +2

    good luck in google

  • @EranM
    @EranM 7 месяцев назад

    This question is NOT easy LOL!

  • @ynng
    @ynng Год назад

    heapq feels like cheating

  • @alexruan5639
    @alexruan5639 2 года назад

    This is pretty confusing.

    • @ninjaturtle205
      @ninjaturtle205 2 года назад +4

      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 2 года назад

      @@ninjaturtle205 🔥🤩

  • @fw4568
    @fw4568 3 месяца назад +1

    Who is here at August 12. 2024?

  • @BikerInsights
    @BikerInsights 3 месяца назад

    anyone here for problem of the day???

  • @numberonep5404
    @numberonep5404 2 года назад

    a cute prb

  • @deepanshurohilla8188
    @deepanshurohilla8188 2 года назад

    C++ solution please

  • @AzimBaghadiya
    @AzimBaghadiya 3 месяца назад

    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?