Sliding Window Maximum - Monotonic Queue - Leetcode 239

Sdílet
Vložit
  • čas přidán 9. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    Coding Solutions: • Coding Interview Solut...
    Problem Link: neetcode.io/problems/sliding-...
    0:00 - Read the problem
    2:20 - Drawing Solution
    12:05 - Coding solution
    leetcode 239
    This question was identified as an Apple interview question from here: github.com/xizhengszhang/Leet...
    #product #apple #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáře • 215

  • @PippyPappyPatterson
    @PippyPappyPatterson Před rokem +129

    The tricky, and didactic, part of this problem is to store index, rather than value, in the deque- which enables you to tell when the bottom of the deque is outside the window.

    • @pranavm002
      @pranavm002 Před 11 měsíci +39

      this should be a pinned comment....the whole drawing part in the video tells us about storing the number in the deque and in the code you store the index and not telling properly why are you doing that is nothing but a scam...

    • @bienvenidovillabroza351
      @bienvenidovillabroza351 Před 11 měsíci +13

      It can still work even if you store the value. Just pop left when nums[left] == deque[0] (only do this after you append to your output list though). Got my submission to reach 99% faster runtime 😅

    • @reggiehurley1479
      @reggiehurley1479 Před 10 měsíci +4

      like the other commentor said - no need for index.

    • @Miggy97
      @Miggy97 Před 10 měsíci +11

      Yeah wouldnt been better if he taught it like this tbh,
      out = []
      r,l = 0,0
      q = collections.deque()
      while r < len(nums):
      while q and q[-1] < nums[r]:
      q.pop()
      q.append(nums[r])
      if r+1 >= k:
      out.append(q[0])
      if nums[l] == q[0]:
      q.popleft()
      l+=1
      r+=1
      return out

    • @SatinderSingh71
      @SatinderSingh71 Před 10 měsíci +3

      Best Solution, less indices to track

  • @Hangglide
    @Hangglide Před 2 lety +158

    Why you give two sorted array for examples? (1,2,3,4 and later 1,1,1,1,4,5) I found it is very hard to follow when you are using sorted array in the example. Why not use 1, 1, 4, 5, 1, 1 instead so that we can see all cases?

    • @piyo1231
      @piyo1231 Před rokem +14

      He gave an unsorted array example at the end (8:26) as well. [8, 7, 6, 9]

    • @Ali-sz1tr
      @Ali-sz1tr Před rokem +49

      completely agree. The first half of the video makes it sound like the input is sorted. If you already know the problem and solution maybe this is not a big deal, but for someone trying to understand the concept if just makes it a lot more unintuitive and confusing.

    • @jointcc2
      @jointcc2 Před rokem +3

      agreed, even though the first two examples are meant to show the extra comparisons can be avoided by a deque, he still could have refined the examples and made it a bit more general

    • @chinmayshetye7899
      @chinmayshetye7899 Před 4 měsíci

      @piyo1231 this code fails for [1,3,-1,-3,5,3,6,7] window 3. Check once and give sol

  • @brecoldyls
    @brecoldyls Před 2 lety +23

    Very cool! Now I am curious to try and apply this data structure to other problems 🤔

  • @dansun117
    @dansun117 Před 3 lety +26

    This is very helpful, thanks so much for sharing it!!

    • @NeetCode
      @NeetCode  Před 3 lety +5

      Thanks, happy it was helpful 🙂

  • @akshaibaruah1720
    @akshaibaruah1720 Před 2 lety +128

    the best part is even if I figure out the solution after struggling, I still come to see your explanation because it's just so beautiful

  • @ChanChan-pg4wu
    @ChanChan-pg4wu Před 2 lety +3

    Always the best, thank you, Neet! I watched your video 3 times to understand the problem.

  • @shoooozzzz
    @shoooozzzz Před rokem +4

    Finally, the monotonic queue data structure makes sense!!! Thank you

  • @chaengsaltz829
    @chaengsaltz829 Před 2 lety +2

    Thank you for your explanation. This is a great help!

  • @charleskorey6515
    @charleskorey6515 Před 2 lety +5

    LC solution is not this elegant as yours. Thanks so much! I was getting stuck on this especially the part where we have to start moving left and right together. In the LC solution, they take care of adding the first k element in the deque separately but your approach is simple and works.

  • @robertjensen7199
    @robertjensen7199 Před 2 lety +12

    Thanks! Small suggestion: `l` can just be `r - k + 1`, which will still do the right thing for the first k elements where it is negative.

    • @PippyPappyPatterson
      @PippyPappyPatterson Před rokem

      What does that do for us besides obviating one line (i.e. the `l = 0` initialization line)?

  • @davidy2535
    @davidy2535 Před 2 lety +2

    thank you for the great explanation! super helpful.

  • @stunning-computer-99
    @stunning-computer-99 Před 2 lety +6

    i must say guys i am not getting this at all surprisingly i am just blank

  • @Rorypandanda
    @Rorypandanda Před 2 lety +1

    Thank you, this was really helpful!

  • @arminphulkar2442
    @arminphulkar2442 Před 2 lety +6

    This problem breaks the common misconception that the window in the sliding window always have to be an array/vector/list, which is not true, look at it, it's a double ended queue, aka. deque!

  • @easifier
    @easifier Před 2 lety +1

    very nice and clear explanation actually, thank you :)

  • @BinaryBenevolence
    @BinaryBenevolence Před 2 lety +2

    This is so nicely explained. thank you

  • @chetanacharekar7914
    @chetanacharekar7914 Před 2 lety +1

    Thanks mate ! It really helps!

  • @mama1990ish
    @mama1990ish Před 2 lety +13

    You have simplified it so well!

  • @aminesfahani3563
    @aminesfahani3563 Před 3 lety +1

    good explanation for monotonically decreasing dequeue method
    many thanks

  • @rohanvishayal8724
    @rohanvishayal8724 Před 11 dny

    This is my first hard problem that I solved by myself, I didn't use deque instead kept tracking the currentMaxIndex manually and updating it manually when it goes out of the window, the solution I wrote is pretty inefficient ( beats 9% LOL) but I did it, my first hard problem, here to check how to solve it properly. Thank you for the explanation.

  • @hoyinli7462
    @hoyinli7462 Před 2 lety

    ur my time hero again!

  • @novasideias531
    @novasideias531 Před rokem

    Man, I really thank you, is 1:58 of the video and I already solved the problem in my mind, while I am in the toilet after wake up😂, the last two days I did 20 problems and whatched your video to understand the solutions that I did not understand

  • @henrylin2008
    @henrylin2008 Před 2 lety +7

    @neetcode, in line #14, if l > q[0], why are we comparing left index to leftmost value in the queue? shouldn't it be value at the left index?

    • @shavitl.306
      @shavitl.306 Před 2 lety

      we know that the leftmost value in the queue is the largest at that point. does this help? I'm confused about this too. did you figure it out? If so, I'd like an explanation please. @NeetCode

    • @ChaosB7ack
      @ChaosB7ack Před 2 lety +4

      I was confused by this too until I noticed his deque contains indexes, not the values themselves. He's comparing the left index to the leftmost index saved in the deque

    • @ChaosB7ack
      @ChaosB7ack Před 2 lety

      @@shavitl.306 ^^^

    • @ChaosB7ack
      @ChaosB7ack Před 2 lety

      I was using the values themselves in my code and I was stunned before realizing we are doing things a bit differently
      class Solution:
      def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
      l = 0
      output = []
      q = collections.deque()
      for r in range(len(nums)):
      while len(q) != 0 and q[-1] < nums[r]:
      q.pop()
      q.append(nums[r])
      if r - l + 1 == k:
      output.append(q[0])
      if q[0] == nums[l]:
      q.popleft()
      l += 1
      return output

    • @pl5778
      @pl5778 Před rokem

      'l' represents the beginning index of the current window, and if that has already passed (larger) than the first element in the deque, that would mean the element in deque is out of bound and no longer applicable to the current window

  • @rentianxiang92
    @rentianxiang92 Před 2 lety +1

    thank you! one step closer to MS

  • @burhanuddinmerchant
    @burhanuddinmerchant Před 2 lety +8

    The condition to check whether the window is of the right size or not is incorrect , it should be "(r-l+1)>=k" instead, it worked in your case, but isn't working now, I suppose they have updated the test cases accordingly. Hope it helps someone who might get stuck at this step. Great explanation given none the less

    • @charleskorey6515
      @charleskorey6515 Před 2 lety +1

      No, it works. The first window ends when r+1 == k. E.g., if k == 2, we should only consider the first 2 elements. In the code after adding those to the deque, the check r+1 == k passes when r == 1. At this time, the front of the deque is put in the output array. Henceforth, r+1 >= k will always remain true as r will increase and at each subsequent next number in the input array a new sliding window forms. First sliding window (l=0,r=1), k=2, next sliding window (l=1,r=2), k=2 etc.

    • @piyusharyaprakash4365
      @piyusharyaprakash4365 Před 11 měsíci

      ​@@charleskorey6515I see.. so as it's a fixed sized window we don't need to do r - l + 1 every time, r+1 works just as well!

  • @cheekyjay7800
    @cheekyjay7800 Před 3 lety +1

    Very clear. Thanks!

    • @NeetCode
      @NeetCode  Před 3 lety +1

      No problem, thanks for watching!

  • @sunnysam69
    @sunnysam69 Před 2 lety +8

    4:21 DJ Khaled!!

  • @sanjanar9198
    @sanjanar9198 Před 2 lety

    Your videos are the best

  • @HarishRaoS
    @HarishRaoS Před rokem

    Thanks for the awesome explanation

  • @linli7049
    @linli7049 Před 3 lety +2

    About the time complexity, we know that each element is added and removed once. I was thinking about the number of comparisons we need when I realize every comparison generates a result: if current number is smaller or deque is empty, add current element to the deque, else remove rightmost element. So the total number of comparisons is equal to the number of insertion and deletion.

    • @linli7049
      @linli7049 Před 3 lety

      Since insertion and deletion is O(N), comparison is O(N), added together still O(N)

    • @propropropropuser
      @propropropropuser Před rokem +1

      @@linli7049 can you elaborate. one would need to compare k times at each number, leading to a runtime of N*K right?

    • @vivekcsdiabolicfreak
      @vivekcsdiabolicfreak Před 3 měsíci

      @@propropropropuser exactly what I was thinking. How can it be O(n)?

  • @alexeymelezhik6473
    @alexeymelezhik6473 Před rokem +2

    IMHO the key idea of the algorithm is not a deque , which is just a tool. The key idea is a competition between TIME and VALUE.
    So we have a "pool" of maximums we've met so far by moving in a time from left to the right and this pull is ordered aways by the time AND by value from left to right in decreasing order. And this pool always expires from the left (in time) as we move further to the left, and expired elements are discarded. So we have two things that "competes" with each other and they are TIME and VALUE ( where time is represented by an index of array ) ... When we pop out elements from the dequeu with values less than then the current element than TIME and VALUE wins ( most recent elements with greater values replace the older elements with less values ). And when we pop out the left most element sometime, this is where TIME wins - no matter the VALUE ( the older elements are eventually gone ).
    So in other words - VALUE is important, by TIME eventually kills even the greatest )))
    But, yeah, great algorithm. It's just an explanation not very intuitive ...

  • @colemanlyski4734
    @colemanlyski4734 Před 9 měsíci +2

    DJ Khaled been real quiet since 4:20 dropped...

  • @chonyy3533
    @chonyy3533 Před 2 lety

    Crystal clear!

  • @harishsn4866
    @harishsn4866 Před rokem +1

    (r + l) >= k - 1 since the indexing starts from 0. I don't know how this code was submitted successfully but I couldn't. While tracing, I realized (r + l) >= k - 1 and my code works pretty fine now.
    Edit: Changed (r + l) to (r - l), still seemed to work pretty well.

  • @stefan.musarra
    @stefan.musarra Před 3 měsíci

    I made some minor modifications which make the logic a little easier to understand. In particular, I appended the current pointer at the top of the loop, and then shift (popleft) the pointers to smaller items from the head.
    #--------------------
    from collections import deque
    def sliding_window_maximum(nums, k):
    output = []
    # deque allows us to shift (popleft) in O(1) time
    # in the queue, we are going to store the index (pointer) to the nums
    # array such that the values are decreasing (the head points to the
    # greatest value)
    q = deque()
    # l = left index of the window
    l = 0
    # the right window pointer is the next value being processed
    # loop all items to be processed
    for r, value in enumerate(nums):
    # increment l after at least k items have been processed
    if r > k -1:
    l += 1
    q.append(r)
    # to keep the queue in decreasing order, the head must be
    # greater than the value just added
    while q and nums[q[0]] < value:
    q.popleft()
    # remove pointers in the queue that are before the current window
    # position
    if q[0] < l:
    q.popleft()
    # after the right window index is at least k, we start adding
    # the greatest value in the window to the output
    if r >= k - 1:
    output.append(nums[q[0]])
    return output
    # added the -4 to the input so code to check the left pointer is executed
    print(sliding_window_maximum([1, 3, -1, -3, -4, 5, 3, 6, 7], 3))
    # [3, 3, -1, 5, 5, 6, 7]

  • @deepsikhakar9166
    @deepsikhakar9166 Před rokem

    great explanation thank you

  • @blueskies3336
    @blueskies3336 Před rokem +1

    That is some big brain solution there lol I have my work cut out for me, dang it! lol

  • @zhaovincent8039
    @zhaovincent8039 Před 2 lety +8

    Hi Sir, I wondered why the time complexity is O(n), but not O(nk)? Since we're useing R pointer looping the array takes O N time, and each time takes O K times to check if the new added pointer R number is greater numbers in the queue?
    Also, the space complexity should be O(k) correct? Since the most elements stored into the queue should be K? We have pop out element once L > q[0], right?

    • @avipatel1534
      @avipatel1534 Před 2 lety +4

      O(n) because we are processing each element twice, once when we add it to the queue and the second time when we remove it from the queue! Space complexity is O(n) because of the output array. It would be O(k) if we disreguard the array

    • @mirrejason4489
      @mirrejason4489 Před rokem

      @@avipatel1534 I think when asking about space complexity, it's always asking about extra space?

  • @yoursandeep
    @yoursandeep Před 2 lety +1

    Hi, May I know what gadget you are using for drawing ? Wanted to buy something like this but not sure which one will appreciate the help.

    • @peacockstar6373
      @peacockstar6373 Před rokem

      In one of his other video's comment, he mentioned he uses Microsoft Paint and a gaming mouse.

  • @yeasinmollik9746
    @yeasinmollik9746 Před 2 lety

    You are the best!

  • @sdaiwepm
    @sdaiwepm Před rokem +1

    To select my teacher going forward, I watched all the videos explaining this problem #239. Your explanation is the best by far. Thank you!

    • @skyhappy
      @skyhappy Před 11 měsíci

      how many viedos was taht total

  • @moveonvillain1080
    @moveonvillain1080 Před měsícem

    I was wondering why it was so easy to figure out at first. Good thing I decided to head here after implementing the brute force solution.

  • @yang5843
    @yang5843 Před 10 měsíci

    Clever solution!

  • @faakhirzahid6284
    @faakhirzahid6284 Před 10 měsíci +1

    I do understand solution but where do u get the basic intuation that this can be solved vai monotonic DS?

  • @shariquekhan8573
    @shariquekhan8573 Před 3 lety +1

    good work!!!

  • @iamsmitthakkar
    @iamsmitthakkar Před 6 měsíci

    If you're like me and the condition "if l > dq[0]:" confuses you, you can rather use "if dq[0] < (r-k+1):" which makes better sense since we are checking if our window is out of bound by checking the first index of dq and r(current indxex) and k

  • @saneerish
    @saneerish Před 2 lety +2

    Can someone please explain why the while loop to clear and add in the deque will not increase the time complexity . I think so my basic concept on this complexity computation are wrong . Can please anyone dumb it down for me

  • @keremt8727
    @keremt8727 Před 8 měsíci +1

    Shouldn't the line 14 be a while loop as we do not pop the leftmost element sometimes (max elem could still be in the range) & sometimes we might have to pop multiples times to compensate for the times we did not pop

  • @prunesalad
    @prunesalad Před 2 lety

    Great video

  • @pratyashasharma1243
    @pratyashasharma1243 Před rokem

    In the drawing solution part, you are adding the elements while in the code you are storing the indices of the elements in the deque. Is there a reason?

  • @saugatkarki3169
    @saugatkarki3169 Před měsícem

    The trick used to store indices was not intuitive at all for me. So, I tried to tweak it to store the numbers instead:
    class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
    que = deque([])
    res = []
    l,r = 0, 0
    for r in range(len(nums)):
    while que and nums[r] > que[-1]:
    que.pop()
    que.append(nums[r])
    if r-l+1 == k:
    res.append(que[0])
    if nums[l] == que[0]:
    que.popleft()
    l += 1
    return res

  • @shreyasipaul7767
    @shreyasipaul7767 Před 2 lety

    Very helpful video ❤️

  • @vishnusunil9610
    @vishnusunil9610 Před 5 měsíci

    Gorgeous !!!!!!!

  • @SohelRana-hi7ec
    @SohelRana-hi7ec Před měsícem

    Awesome.!

  • @guitarist3917
    @guitarist3917 Před rokem

    quick question, I believe the last if statement should be if(r-left+1)>=k, right? because we are calculating the window size

  • @akagamishanks7991
    @akagamishanks7991 Před 6 měsíci

    im confused bc in order for the algorithm to work the array has to be sorted right?

  • @ameynaik1755
    @ameynaik1755 Před 3 lety +8

    When does l > q[0] encountered?? basically when do we popleft? I think we should popleft when l == q[0]. Can you please confirm? @neetcode

    • @shankiyani
      @shankiyani Před 2 lety

      Because line 20 executes before line 15. For example is k = 1, then on the first pass the condition l > q[0] is false because 0 == 0. But we have reached the window size and therefore enter the next conditional statement and increment the startWindow. A better condition for checking the window size is r - l + 1 == k.

    • @ChaosB7ack
      @ChaosB7ack Před 2 lety +2

      I was confused by this too until I noticed his deque contains indexes, not the values themselves. He's comparing the left index to the leftmost index saved in the deque

  • @noobCoder26
    @noobCoder26 Před 2 lety

    superb soln sir.

  • @orellavie6233
    @orellavie6233 Před 2 lety +1

    Maybe double linked list with head and tail pointers, this trick of deque is aweful (O(1) pop and popleft). After that, the solution is valid

  • @ebbissachemeda4815
    @ebbissachemeda4815 Před rokem

    nice explanation

  • @jayaramv8131
    @jayaramv8131 Před 6 měsíci

    There's a small correction in the code
    if (r + (l+1)) >= k:
    res.append(nums[q[0]])
    l += 1
    We should be checking (r + (l+1)) >= k because for (l = 0, r = 2) 2 >= 3 will not satisfy for k = 3

  • @jp-wi8xr
    @jp-wi8xr Před 3 měsíci

    Can you explain the O(n) DP sol, where we divide the array in blocks of k and calculate max_left and max_right ?

  • @nobiased007
    @nobiased007 Před 3 lety

    Excellent

  • @CHUAN-CHI
    @CHUAN-CHI Před 5 měsíci

    Awesome❤

  • @vivekcsdiabolicfreak
    @vivekcsdiabolicfreak Před 3 měsíci

    How is this O(n); one would need to compare k times at each number, leading to a runtime of N*K right?

  • @sipwhitemocha
    @sipwhitemocha Před rokem +1

    Could someone explain me on O(K * (n - k)) at @2:04?
    Using the provided example, there are n = 8 and k = 3 which would yield 15 using the complexity algorithm. However, the maximum window is only 6 so I am super confused.
    Please note that my experience is very little

    • @danny65769
      @danny65769 Před rokem +4

      It should be O(k * (n - k + 1)) because there are (n - k + 1) windows.

  • @alexguo7343
    @alexguo7343 Před 10 měsíci

    My solution that passes on LC:
    I feel as this is more consistant with the way neetcode solved the other ones. Exact same algo
    class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
    q = deque()
    l = 0
    res = []
    for r in range(len(nums)):
    while len(q) != 0 and nums[r] > nums[q[-1]]:
    # pop all smaller elements from queue
    q.pop()
    q.append(r)
    if r - l + 1 == k:
    res.append(nums[q[0]])
    if r - l + 1 > k:
    l += 1
    while q[0] < l:
    q.popleft()
    res.append(nums[q[0]])
    return res

  • @studyaccount794
    @studyaccount794 Před 2 lety +1

    Great explanation!! But how can we know when to pop and when not to from the start of the array. In the first example we don't pop from the left while in the 2nd one we did pop from the left??

    • @javascriptbrains8080
      @javascriptbrains8080 Před rokem

      You need to maintain a left pointer and keep checking if left > queue most left element as we have to update window while moving to right.

  • @mingjuhe1514
    @mingjuhe1514 Před 2 lety

    Great!

  • @amanueltsehay3119
    @amanueltsehay3119 Před rokem

    Thanks

  • @NinjiaJoeLife
    @NinjiaJoeLife Před 2 lety +1

    from your explaination, you stored the value in q, then why use q.append(r) instead of q.append(nums[r]). Why storing the indices

  • @user-dm9id4iv7q
    @user-dm9id4iv7q Před 9 měsíci

    i found this can be solved without using a deque rather an array/vector with left counter. if possible make a video on that.
    thankx

  • @chengyiliu2277
    @chengyiliu2277 Před 3 lety +2

    Doesn't "pop smaller element from queue take O(k) time? in the worst case, you have to look at every element in the queue?

    • @akshaibaruah1720
      @akshaibaruah1720 Před 2 lety +4

      we are maintaining the deque in such a way that left is max and right is min
      How?
      when we are about to push an element, we remove all the smaller ones(two reasons : 1. when we find a greater element, the smaller ones are never gonna be max so they are useless 2.When we remove the smaller ones from the right, and then put the current element the rightmost one is still the smallest now)
      try drawing the deque in a paper and you will get it
      this is kind of like the pattern search algo, just that we need deque for its functions

    • @reggiehurley1479
      @reggiehurley1479 Před 10 měsíci

      i had same question but apparently deque is constant on both sides lol

  • @geekydanish5990
    @geekydanish5990 Před rokem

    Solved using both max heap and queue
    class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
    # i,j = 0,0
    # max_heap = []
    # res= []
    # while j < len(nums):
    # # removing all prev added samller num compare to the curr_num
    # while max_heap and -max_heap[-1] < nums[j]:
    # max_heap.pop()
    # # add the curr_num into heap
    # heapq.heappush(max_heap, -nums[j])
    # # reached the window of size k
    # if j-i+1 == k:
    # # add the max in element in the windows size of k
    # max_num = -max_heap[0]
    # res.append(max_num)
    # if max_num == nums[i]:
    # heapq.heappop(max_heap)
    # i+=1
    # j+=1
    # return res
    i,j = 0,0
    res = []
    queue = deque()
    while j < len(nums):
    # queue's monotonic dc order breaks
    while queue and queue[-1] < nums[j]:
    queue.pop()
    queue.append(nums[j])
    if j-i+1 == k:
    max_num = queue[0]
    res.append(max_num)
    if max_num == nums[i]:
    queue.popleft()
    i+=1
    j+=1
    return res

  • @Brtang-x1r
    @Brtang-x1r Před 2 lety +1

    In the example with 1s, 4 and 5, what if 4 was in position 1 of the array? How would the deque keep track of when 4 goes out of bounds in the window ? If the purpose of the deque is to keep track of the position within the window, we would need to keep track of the max and not just use the left most in the deque?

    • @lemonke8132
      @lemonke8132 Před rokem

      yeah dude i swear to god on every neetcode video I have 1 burning question that he never addresses. It's honestly starting to piss me off

    • @kthtei
      @kthtei Před rokem

      Explanation doesn't cover these things which is a bit annoying.

  • @lindama1276
    @lindama1276 Před rokem

    Why is it o(n) if you're having the inner while loop?

  • @darshansimha2166
    @darshansimha2166 Před 2 lety +7

    Using (right - left + 1) % k == 0 over right + 1 >= k would have made the code more intuitive and readable IMO. Nice explanation though.

    • @gladyouseen8160
      @gladyouseen8160 Před 2 lety

      Please share your code

    • @zhaovincent8039
      @zhaovincent8039 Před 2 lety +3

      Great hit, also can just do (right - left + 1) == k is fine.

    • @zhaovincent8039
      @zhaovincent8039 Před 2 lety

      @@gladyouseen8160 just need change that line 17 condition in the video.

  • @oximas-oe9vf
    @oximas-oe9vf Před rokem

    hopfully i can understand this one day

  • @dharamthakkar
    @dharamthakkar Před 2 lety +1

    Thanks @NeetCode! That's really useful.
    Isn't below more simple solution?
    class Solution:
    def sumOfSlidingWindow(self, nums: List[int], k : int) -> List[int]:
    output = []
    for w in range(len(nums)-k+1):
    output.append(max(nums[w:w+k]))
    # 1,3,-1,-3,5,3,6,7
    return output

    • @maxsuica6144
      @maxsuica6144 Před 2 lety +2

      This is a simpler algorithm.
      However, max(nums[w:w+k]) requires O(k) work, and you run it O(n) times, so the runtime is O(n*k).
      Suppose n = 1,000,000 and k = 2,500. Now, if you double the window size to k = 5,000. Now you're maxing 5,000 elements per window slice, so it will run 2x slower.
      In @NeetCode's solution, increasing the window size *doesn't* increase the runtime at all! That's what justifies the more complicated solution.

  • @mayankpant5376
    @mayankpant5376 Před 2 lety

    Will it be linear if we use heap and keep on adding the new element in the window to heap and getting maximum element from heap .

  • @pranavm002
    @pranavm002 Před 11 měsíci

    i have looked into leetcode discussions section and everywhere possible to understand what exactly the following line does
    while d and nums[d[-1]] < nums[r]:
    d.pop()
    nobody properly explains what it even does and why its necessary, not even this video.

  • @light_70
    @light_70 Před 10 měsíci

    thanks :)

  • @edwardteach2
    @edwardteach2 Před 2 lety

    U a God

  • @satyamm9901
    @satyamm9901 Před 29 dny

    neetcode: "These elements are useless to us"
    elements: *sad min element noises*

  • @marcusaurelius6607
    @marcusaurelius6607 Před rokem

    queue is really inefficient here, normally every element is allocated on heap, so you screw cpu cache lines. better used ring buffer, solves all the issues

  • @lightwerner7248
    @lightwerner7248 Před 11 měsíci

    from typing import List
    import collections
    class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
    """
    Find the maximum sliding window in an array of integers.
    Args:
    nums (List[int]): The input array of integers.
    k (int): The size of the sliding window.
    Returns:
    List[int]: The list containing the maximum values in each sliding window.
    Example:
    Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
    Output: [3, 3, 5, 5, 6, 7]
    """
    q, res = collections.deque(), [] # Use a deque for efficient operations.

    # Iterate through the array from left to right.
    for r in range(len(nums)):
    # Remove smaller elements from the deque.
    while q and nums[r] > nums[q[-1]]:
    q.pop()

    # Add the current index to the deque.
    q.append(r)

    # Check if the window has enough elements.
    if r + 1 < k:
    continue

    # Check if the leftmost element is outside the window [r+1-k, r], remove it from the deque.
    # checking if the index at q[0] is smaller than left = r+1-k, if it is then just pop the index at left
    if q[0] < (r + 1 - k):
    q.popleft()

    # Append the maximum value in the current window to the result list.
    res.append(nums[q[0]])

    return res

  • @gregoryvan9474
    @gregoryvan9474 Před 2 lety

    Does the company logo in the thumbnail of each video indicate that the problem was asked before in an interview with that company? For example, for this video it is more likely to be asked in a Google interview?

    • @xijinping5064
      @xijinping5064 Před rokem

      "Does the company logo in the thumbnail of each video indicate that the problem was asked before in an interview with that company?" Yes

  • @i.eduard4098
    @i.eduard4098 Před rokem

    Ok, as I researched yesterday on sliding window topic, this problem doesn't seem Hard by I have doubts, it should be hard..

  • @aquibulhaqchowdhury4542
    @aquibulhaqchowdhury4542 Před 8 měsíci

    Am I the only one who thought to use a binary search tree (multiset in C++) on their first try? The time complexity of this approach O(n log k), worse than the deque solution which is O(n). However the BST solution worked within the time limit.

  • @chengyiliu2277
    @chengyiliu2277 Před 2 lety

    I am a little confused since you pop and add element from the same side of the queue, does the queue function the same as a stack?

    • @792147019
      @792147019 Před 2 lety

      My guess is in python stack is implemented based on array where popleft requires left-shift of each element taking O(n), and the deque works like a double linked list where popleft is just delete the leftmost node, which is O(1)

    • @charleskorey6515
      @charleskorey6515 Před 2 lety +1

      In python, deque is used for queue. In C++, we have queue, stack and deque

  • @tb8588
    @tb8588 Před 2 lety +2

    I have a question, why the time O(n) ? I thought it would be something like O(nk) cuz when we do popping out from the deque, wouldn't that cause some additional time as well?

  • @rutvijsupekar4543
    @rutvijsupekar4543 Před 2 lety

    Very easy to understand and concise.

  • @atefe3919
    @atefe3919 Před 3 lety +5

    Hi, I am confused about the part we check for the size of the window, why R + 1 >= k ?

    • @matthewtang1490
      @matthewtang1490 Před 3 lety +2

      I think it's because when you go from index -> length we increment by 1. So when we compare r (which is an index) to k (which is a length) to make a comparison r needs to be incremented by 1

    • @rahul5794
      @rahul5794 Před 3 lety +4

      That's there only for the first time.
      In the first iteration you are starting with l and r both equal to 0
      So you skip the if condition until r < k
      But when r becomes >=k it means we have reached to the point where our sliding window is full with size = k
      Now it's implied that in each of the next iterations our sliding window will always be full with size = k
      So, in each iteration we add the max element to the output array

    • @Windows7Air
      @Windows7Air Před 3 lety +12

      u can also do (r-l + 1) == k

  • @user-dp9gi1vg8r
    @user-dp9gi1vg8r Před 2 měsíci

    bro i love u

  • @CyberMew
    @CyberMew Před 3 lety +3

    Is this monotonic queue method directly applicable for LC739. Daily Temperatures? Edit: saw it here: czcams.com/video/cTBiBSnjO3c/video.html

  • @pseudounknow5559
    @pseudounknow5559 Před rokem

    can someone explain :
    if (i > dq.front()) {
    dq.pop_front();

  • @RandomShowerThoughts
    @RandomShowerThoughts Před 2 měsíci

    hm, idk that explanation seemed to work when the inputs were sorted. I get it still works, but I'm a bit confused lol

  • @lightwerner7248
    @lightwerner7248 Před 11 měsíci

    if l > q[0]:
    q.popleft()
    did not understand this part. Can anyone explain as if I understand nothing?

  • @chendong2197
    @chendong2197 Před 2 lety +1

    Find it a bit confusing to use two pointers, l and r, both of which increment 1 each time. Since this is a fixed window, it make more sense just to have one right pointer.

    • @eduardobautista5195
      @eduardobautista5195 Před 2 lety

      I agree with you. I think it's convention to have two pointers in sliding window problems, but in cases like this it's easier to have one pointer.

    • @broccoli322
      @broccoli322 Před rokem

      I agree.

  • @nikhilgoyal007
    @nikhilgoyal007 Před rokem

    thanks! Can someone pls tell me why lines 14 exist ? i.e. if l > q[0]: q.popleft() . I understand the q.popleft but just not able to understand the 'if' statement preceding it. thanks so much!

    • @nikhilgoyal007
      @nikhilgoyal007 Před rokem

      Got it now. I missed they were indices and was thinking them of as values somehow.