Last Stone Weight - Priority Queue - Leetcode 1046 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ส.ค. 2024

ความคิดเห็น • 63

  • @josephzhang4607
    @josephzhang4607 ปีที่แล้ว +12

    Instead of working with flipped negative values, for the sake of clarity, I've implemented my code to convert these values each time.
    Python code:
    class Solution
    def lastStoneWeight(self, stones: List[int]) -> int:
    #implement a maxheap
    negativeHeap = [-x for x in stones]
    heapq.heapify(negativeHeap)
    while len(negativeHeap) > 1:
    largest = -1 * heappop(negativeHeap)
    largest2 = -1 * heappop(negativeHeap)
    if largest2 < largest:
    heappush(negativeHeap, -1 * (largest - largest2))
    return -1 * negativeHeap[0] if negativeHeap else 0

    • @spiffylogic
      @spiffylogic 7 หลายเดือนก่อน +3

      No need to multiply by -1, just negate. i.e. "-x" instead of "-1 * x".

  • @harishsn4866
    @harishsn4866 2 ปีที่แล้ว +24

    Still waitin' for the Last Stone Part 2 video. 💀 💀 💀

    • @jayberry6557
      @jayberry6557 ปีที่แล้ว +8

      He said tomorrow. Be patient.

    • @chris0617
      @chris0617 3 หลายเดือนก่อน

      ​@@jayberry6557nah. Still waiting

  • @ilanaizelman3993
    @ilanaizelman3993 2 ปีที่แล้ว +16

    Love your videos! Will probably comment on every video, trying to bing all of ur videos. and solve most of them using your amazing explanations and cleanest code solutions I've ever seen.
    Also joined your channel!

    • @NeetCode
      @NeetCode  2 ปีที่แล้ว +5

      Thank you so much, I really appreciate it!!!

  • @jessepinkman566
    @jessepinkman566 2 ปีที่แล้ว +8

    Hi, Can you do Last Stone Weight II? Thanks

  • @erik-sandberg
    @erik-sandberg 2 ปีที่แล้ว +4

    at 3:24 you say the time complexity to get the maximum is O(logn), but is it actually O(1)?

    • @nishankpriydarshi3984
      @nishankpriydarshi3984 2 ปีที่แล้ว

      yes, the overall complexity should be O(n) ig

    • @Denolth
      @Denolth 2 ปีที่แล้ว +14

      Popping from the heap is a O(logn) operation. By "get the maximum", Neetcode meant popping. The price of O(1) is for just looking at the maximum, but popping is more expensive.

  • @utkarshsaboo
    @utkarshsaboo 3 ปีที่แล้ว +3

    Hey Neetcode! This is my last resort lol but can you please solve Basic Calculator 1? I've seen every resource on the net and I am yet to find one that really nails the concept. I love your videos and I am sure you will explain it beautifully!

  • @prog5724
    @prog5724 ปีที่แล้ว +3

    more understandable for me
    def lastStoneWeight(self, stones: List[int]) -> int:
    stones = [-s for s in stones]
    heapq.heapify(stones)
    while len(stones) > 1:
    first, second = heapq.heappop(stones), heapq.heappop(stones)
    diff = - abs(first-second)
    heapq.heappush(stones, diff)
    return abs(stones[0])

    • @bouzie8000
      @bouzie8000 6 หลายเดือนก่อน

      exactly

    • @erickmercado1711
      @erickmercado1711 4 หลายเดือนก่อน

      @@bouzie8000 what is the point of the -abs? isn't that redundant because you are already doing return abs()

    • @treytzee
      @treytzee 15 วันที่ผ่านมา

      @@erickmercado1711 in the case there is a remaining diff, the negative helps it stay consistent when you push it back into the "max heap"

  • @nadhiyaganesan2161
    @nadhiyaganesan2161 ปีที่แล้ว +2

    My interview prep starts here !!! Thanks a lot :)

  • @LunaFlahy
    @LunaFlahy ปีที่แล้ว +2

    Thank you for sharing this solution.
    I am working on my clarity of code.
    Here are what I learned from your code.
    1. use a list initializer to store negative values.
    2. use heapq.heapify , O(N), instead of in a for loop to heapq.heappush, O(NlogN)
    3. pop the items out first, then compare them to decide whether to push or not. I compare them first, which results in redundant code.
    4. last 2 lines are smart. append(0) in case the heap is empty. It's okay for me to use` return 0 if not heap else abs(stone[0])` though.

  • @chamikaonyt
    @chamikaonyt ปีที่แล้ว

    class Solution {
    public:
    static int lastStoneWeight(vector& stones) {
    // heapify -> O(n)
    make_heap(stones.begin(), stones.end());
    while (stones.size() > 1){ // O(n)
    int first = stones.front();
    pop_heap(stones.begin(), stones.end()); // log n
    stones.pop_back();
    int second = stones.front();
    pop_heap(stones.begin(), stones.end()); // log n
    stones.pop_back();
    if (first != second){
    // Note that the push_heap function assumes that the heap property is already satisfied for all elements except the last one.
    stones.push_back(first - second);
    push_heap(stones.begin(), stones.end()); // log n
    }
    } // Total time ==> n * (log n + log n + log n) === O (n log n)
    if (stones.size() == 1){
    return stones[0];
    }
    else{
    return 0;
    }
    }
    };

  • @harsh9558
    @harsh9558 2 ปีที่แล้ว

    My approach(wrong):
    sort(stones.begin(), stones.end());
    int sum1 = stones[0], sum2 = 0;
    for(int i = 1; i < stones.size(); i++)
    {
    if(sum1 > sum2) sum2 += stones[i];
    else sum1 += stones[i];
    }
    return abs(sum1 - sum2);
    keep 2 variables sum1 & sum2
    if(sum1 greater) add to sum2 else to sum1
    Does the order of adding matters? Shouldn't this work?

  • @dsa0decoded
    @dsa0decoded 5 หลายเดือนก่อน

    Hey I've found out that checking case is redundant here because it will be the case every time as in minheap second elem always gonna be greater than first (or if equal then it will push 0 to the heap so we dont have to append an 0 at the end by ourselves)

  • @bigrat5101
    @bigrat5101 ปีที่แล้ว +3

    you can also use sort() and grabbing the last 2 nums to get the difference if there is any. then once the while loop breaks out, you can either return stones[0] if len ==1. else just return 0.

  • @hamoodhabibi7026
    @hamoodhabibi7026 2 ปีที่แล้ว +3

    At 11:56 when checking for edge case you wrote "stones.append(0)" I was wondering if this is allowed because we use a list function for a heap structure. I'm just making sure because this might be a loop hole since python is so laxed. If so wonderful python is awesome :D

    • @Cudifer
      @Cudifer 2 ปีที่แล้ว +4

      It's ok because stones is still a list type, the list will just follow the heap structure when heapify if called - also, stones[0] will not change no matter how much you append to it.

    • @ericgoto5166
      @ericgoto5166 7 หลายเดือนก่อน

      i think its bad coding..

  • @etonemoilogin
    @etonemoilogin ปีที่แล้ว

    abs() call is unnecessary because all stones have negative weight. So it is more clear to use "return -stones[0]" to be in sync with weights negation at start.

  • @potatocoder5090
    @potatocoder5090 2 ปีที่แล้ว +2

    Thank you for the solution! I have a doubt though: Could you please explain why converting a list to a heap has O(n) time complexity ? Shouldn't it take O(nlogn) time?

    • @junjason4114
      @junjason4114 2 ปีที่แล้ว

      This course will answer your question. th-cam.com/video/B7hVxCmfPtM/w-d-xo.html

    • @hamoodhabibi7026
      @hamoodhabibi7026 2 ปีที่แล้ว +2

      because your going through the list stones in linear time one by one putting them in a heap structure.

    • @qingfengcao6852
      @qingfengcao6852 2 วันที่ผ่านมา

      This is because he converted the list into a heap using the heapify algorithm, which is O(n). Heapify builds the heap structure from bottom to top. If you build the heap structure from top to bottom, the time complexity will be O(nlogn),

  • @abhilashkumarpalem461
    @abhilashkumarpalem461 3 ปีที่แล้ว +1

    Hi Neetcode, Thanks for all the amazing explanations. If possible, can u please make a video on Generalized Abbreviation problem

  • @boluobao-k3m
    @boluobao-k3m ปีที่แล้ว +1

    python's amazing... in JS, you need to write your own Heap first...

  • @fawazkhalid4421
    @fawazkhalid4421 3 ปีที่แล้ว +1

    Awesome. Could you do one for Maximum Area of a Piece of Cake? Thanks!

  • @brooks7845
    @brooks7845 2 ปีที่แล้ว

    You make it look so easy!!!

  • @jagadeeshsatya
    @jagadeeshsatya 3 หลายเดือนก่อน

    //Just an 8-line code, but I used built-in functions more often in the code.//
    def last_stone_weight(arr):
    while len(arr)>1:
    arr.sort()
    a,b=arr.pop(),arr.pop()
    arr.append((a-b) if (a>b) else (b-a))
    print(arr[0])
    arr=[2,7,4,1,8,1]
    last_stone_weight(arr)

  • @slizverg23
    @slizverg23 ปีที่แล้ว +2

    Isn't it O(1) to pop a max from the heap?

    • @IPatricio
      @IPatricio 5 หลายเดือนก่อน

      Not popping because it has to reorganize the rest of the heap to correct for it. If it was just getting to top of the heap then yeah.

  • @rajdeepbhavanarushi4887
    @rajdeepbhavanarushi4887 22 วันที่ผ่านมา

    This was asked in NVIDIA interview

  • @Robert-ht5kd
    @Robert-ht5kd 6 หลายเดือนก่อน

    I think it is over complication to use heap in this case, there is max 30 stones in the list, so using list pop() and sort() methods is simpler and better solution.

  • @amogchandrashekar8159
    @amogchandrashekar8159 3 ปีที่แล้ว +1

    Thanks!

  • @julianalvarez2290
    @julianalvarez2290 2 ปีที่แล้ว

    Nice, Clean Code!

  • @spiffylogic
    @spiffylogic 7 หลายเดือนก่อน

    Just negate the values coming out the heap and avoid the confusion. It's a single character (-). No need to multiply or use absolute value.
    first = -heapq.heappop(stones)
    second = -heapq.heappop(stones)

  • @aaronpuah918
    @aaronpuah918 3 ปีที่แล้ว +4

    Looking forward to Last Stone Weight II explanation

  • @codediva007
    @codediva007 3 หลายเดือนก่อน

    can you please explain the most optimized solution for this problem?

  • @EranM
    @EranM 4 หลายเดือนก่อน

    I love your voice mate!

  • @user-oc6ky2tk5o
    @user-oc6ky2tk5o 2 ปีที่แล้ว

    Thank you !

  • @sanooosai
    @sanooosai 5 หลายเดือนก่อน

    thank you

  • @symbol767
    @symbol767 2 ปีที่แล้ว

    Thanks man, liked

  • @mayankmaheshwari2544
    @mayankmaheshwari2544 2 ปีที่แล้ว

    is the time complexity of the solution is O(n*3*log(n)) ?

  • @Dionmok111
    @Dionmok111 10 หลายเดือนก่อน

    Great example! After running through the algorithm thoroughly, there is no need for the conditional "if" because the Max Heap will always maintain the top 2 highest values.
    def lastStoneWeight(self, stones):
    """
    :type stones: List[int]
    :rtype: int
    """
    stones = [-s for s in stones]
    heapq.heapify(stones)
    while len(stones) > 1:
    num1 = heapq.heappop(stones)
    num2 = heapq.heappop(stones)
    heapq.heappush(stones, num1 - num2)
    return abs(stones[0])

  • @kiki-yq1fk
    @kiki-yq1fk 2 ปีที่แล้ว

    Nice vid!

  • @sowmyamruthyunjaya6358
    @sowmyamruthyunjaya6358 3 ปีที่แล้ว +1

    Awesome

  • @akashuday7107
    @akashuday7107 ปีที่แล้ว

    the second will always be greater right ? i mean why is the if second> first even required?

    • @justmeandmy
      @justmeandmy 5 หลายเดือนก่อน

      They might be equal

  • @samriddhashukla5345
    @samriddhashukla5345 ปีที่แล้ว +1

    Bro make a part 2 video please.

  • @vaibhavrbs
    @vaibhavrbs 2 ปีที่แล้ว

    why don't you use abs(max(first, second)) and abs(min(first, second)) to get bigger_stone and smaller_stone respectively.?

    • @hamoodhabibi7026
      @hamoodhabibi7026 2 ปีที่แล้ว +1

      because we already know which one is the bigger stone since we got it from the modified min heap

  • @Kaustubhmokal
    @Kaustubhmokal 27 วันที่ผ่านมา

    I have a question, since you are a big youtuber now, when we comment about how useful your videos are, do you still care ? I mean, does it make u happy ?

  • @gaurav91pandey
    @gaurav91pandey 3 ปีที่แล้ว +5

    Great video! Just one criticism: please don't put hints (Priority Queue) in the video title. I like to try the problem myself first and then see how you do it. Thanks.

  • @szeryk324
    @szeryk324 11 วันที่ผ่านมา

    It turns out Python has max_heap implementation in heapq, it's just private and not documented for some reason. And I couldn't use _heappush_max, but can live without it :P
    def lastStoneWeight(self, stones: List[int]) -> int:
    # max heap is not a public member of heapq, rather a private one
    heapq._heapify_max(stones)
    while len(stones) > 1:
    a = heapq._heappop_max(stones)
    b = heapq._heappop_max(stones)
    if a != b: # a is NEVER less than b
    # there's no _heappush_max(), need to use heapify...
    stones.append(a - b)
    heapq._heapify_max(stones)

    return stones[0] if stones else 0