Daily Temperatures - Monotonic Stack - Leetcode 739 - Python

Поділитися
Вставка
  • Опубліковано 1 чер 2024
  • 🚀 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 - ...
    Problem Link: neetcode.io/problems/daily-te...
    0:00 - Read the problem
    1:51 - Drawing Explanation
    9:25 - Coding Explanation
    leetcode 739
    This question was identified as a facebook interview question from here: github.com/xizhengszhang/Leet...
    #monotonic #stack #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Наука та технологія

КОМЕНТАРІ • 117

  • @shaisundar7116
    @shaisundar7116 Рік тому +203

    A small optimization - you need not store the (key, index) pair. You can just store the index in the queue. For each comparison just reference the array with the index in the queue. Got a faster compute and lesser space.

    • @asmaahamdy48
      @asmaahamdy48 Рік тому +3

      Great tip
      Thanks

    • @festraider
      @festraider 11 місяців тому +3

      Kyu(queue)

    • @bryanleow5024
      @bryanleow5024 9 місяців тому +20

      for anyone wondering how the code will look like with this modification (imagine a "sliding window" technique of comparing index l and index r):
      answer = [0] * len(temperatures)
      stack = []
      for r in range(len(temperatures)):
      while stack and temperatures[stack[-1]] < temperatures[r]:
      l = stack.pop()
      answer[l] = r-l
      stack.append(r)
      return answer

  • @nguyen-dev
    @nguyen-dev Рік тому +83

    The first time hearing monotonic stack. The solution provided in leetcode with space complexity O(1) is even more amazing!!! This problem to me is too hard. I was only able to find brute force solution before watching this video and see leetcode solutions tab.

    • @justsvk1500
      @justsvk1500 Рік тому +63

      dw man.. the more you don't know and the more you look it up when you don't know, the more patterns you'll recognise later

  • @swapneelchakraborty3553
    @swapneelchakraborty3553 9 місяців тому +8

    Got TLE exception with the n^2 solution, thanks for this approach

  • @Nekaelia
    @Nekaelia 10 місяців тому +15

    I found this one really hard, i was only able to find a brute force solution. Thank you for the clean explanation. ^_^

  • @belindaqi243
    @belindaqi243 2 роки тому +2

    Your coding tutorial helped me so much. Thank you.

  • @MrjavoiThe
    @MrjavoiThe Рік тому +8

    This is so hard not beginner at all, there must be way easier problems covering the basics and more beginner friendly than this, no way someone solved this way, without solving similar problems like this before.

  • @EmilyHopeGrove
    @EmilyHopeGrove 2 місяці тому +2

    I THINK this is a mis-speak here at 10:17, you say "first thing we're going to do is see is our stack empty, and if it is ... " I believe you meant to say "if it's NOT empty, and if it's not ..." (meaning there is indeed something inside the stack).
    To be clear -
    ```while stack and t > stack[-1][0]:``` - This while loop runs as long as stack is not empty and the current temperature t is greater than the temperature at the top of the stack (stack[-1][0]).
    Hope this helps someone who was just as confused as I was about why we would be able to get the temperature and index out of an empty stack 😂
    (This is not to criticize the world's greatest human on the planet for helping us lowly juniors get a handle on leetcode, it's just to help clarify for anyone who may have been confused).

  • @vaishnavejp9247
    @vaishnavejp9247 9 місяців тому +7

    I am currently doing you roadmap. My god, thank you so so so much for that. I am so grateful for that. It truly has helped grinding leetcode fun.

  • @haifzhan
    @haifzhan 2 роки тому +6

    Clean explaination!

  • @sukhadakulkarni1511
    @sukhadakulkarni1511 2 роки тому +6

    Love your videos! Thanks for the efforts!

  • @jessw4195
    @jessw4195 4 місяці тому +3

    This was the first problem following Neetcode Roadmap that I was able to do by myself since I started studying two weeks back. Thanks for these videos!

  • @nazninmalek4440
    @nazninmalek4440 2 роки тому +18

    Another way is to traverse from right to left in an array and start building a stack, that way for every position we should be able to find next warmer temperature on top of the stack

    • @anantprakashsingh8777
      @anantprakashsingh8777 Рік тому +1

      Can you please share the code for this approach, I was trying to build a solution in a similar manner but couldn't really come to a conclusion. Thanks!

    • @krushnapatil9196
      @krushnapatil9196 Рік тому +2

      @@anantprakashsingh8777 leetcode pr discussion mein hai

    • @abhinavchoukse2357
      @abhinavchoukse2357 7 днів тому

      @@anantprakashsingh8777 I too tried this approach and here's how my solution looks like:
      class Solution {
      public:
      vector dailyTemperatures(vector& temperatures) {
      int n = temperatures.size();
      vector res(n, 0);
      stack st;
      st.push(make_pair(temperatures[n-1], n-1));
      for(int i=n-2; i>=0;i--){

      while(!st.empty() && st.top().first

  • @brownboyintokyo7368
    @brownboyintokyo7368 Рік тому

    best explainer of leetcode problems on the internet

  • @lixiaolong800
    @lixiaolong800 3 місяці тому

    Made so clear! Thank you.

  • @siddhantkhanna9053
    @siddhantkhanna9053 Рік тому

    great visual explanation!!

  • @asmaahamdy48
    @asmaahamdy48 Рік тому

    Great Explanation as always
    Thank you

  • @narendrakumariitb
    @narendrakumariitb 2 роки тому +9

    Thanks for neet explanation 😊 Also I think we can solve it iterating from end as well

    • @n.h.son1902
      @n.h.son1902 Місяць тому

      How did you solve it by iterating from the end?

  • @MP-ny3ep
    @MP-ny3ep 4 місяці тому

    Great explanation as always. Thank you .

  • @amirhatamzad
    @amirhatamzad Рік тому

    amazing explanation dude, thank you

  • @samarthtandale9121
    @samarthtandale9121 Рік тому

    Wow 😲 ... Brilliant solution!

  • @saurabhmarne9595
    @saurabhmarne9595 2 роки тому +3

    How do I get from Brute force approach to this (or such) optimized solution?

  • @symbol767
    @symbol767 2 роки тому

    Thanks man, liked and commented for support

  • @JCT836
    @JCT836 2 місяці тому

    Thanks! Great explanation!

  • @BTECESaumyaPande
    @BTECESaumyaPande 2 роки тому

    Thankyou for helping us.

  • @e555t66
    @e555t66 2 роки тому +1

    Beautiful videos.

  • @sathyanarayanankulasekaran5928
    @sathyanarayanankulasekaran5928 2 роки тому

    Brilliant AF !!!!!!!!

  • @marcelsantee1809
    @marcelsantee1809 7 місяців тому +2

    O(n)?
    Shouldn't we take in consideration the while loop? In worst case, might take long.

  • @AdityaKumar-ec5th
    @AdityaKumar-ec5th 3 місяці тому

    thank you mr. neet

  • @kobeissi721
    @kobeissi721 2 роки тому +5

    Thanks! I did solve it but my mind jumped straight to DP (Like LIS) but it was pretty inefficient.

    • @samarthtandale9121
      @samarthtandale9121 Рік тому +3

      Same bro ... In fact I have seen a pattern that the problems involving monotonic stack or monotonic queue often make us think it's about dp !

    • @EduarteBDO
      @EduarteBDO 4 місяці тому

      Same. My head was stuck in dp until I saw the topics then I oh it's a stack problem. I mean there's some kind of memoization with monotonic stack

  • @zhuofanli9985
    @zhuofanli9985 Рік тому

    Fantastic!

  • @elitea6070
    @elitea6070 День тому

    Man this question is annoying its basically "if you know this you know it" aint no way I was gonna do it without this video

  • @kirillzlobin7135
    @kirillzlobin7135 7 місяців тому

    Thank you!!!

  • @leozindabala
    @leozindabala 10 місяців тому

    whats the tool you use for drawing the solutions?

  • @riceball100
    @riceball100 2 роки тому +1

    Where does the variable stackT get used in the example code at 11:46 inside of the while loop?

    • @lgeochipl
      @lgeochipl Рік тому +2

      It doesn't. There is no need to add a pair [temp, index] to the stack -- just index is enough.

  • @Iamnoone56
    @Iamnoone56 2 роки тому +3

    there is a O(1) space soln there on leetcode

  • @hrsight
    @hrsight 2 місяці тому

    Good video.

  • @lsquang1
    @lsquang1 2 роки тому +3

    This is extremely useful even though I code in c++.

    • @TheElementFive
      @TheElementFive 2 роки тому +49

      Cpp coders want everyone to know they code in cpp. They’re like vegans 😅

  • @MrWuggles
    @MrWuggles 7 місяців тому +1

    Great solution explanation, although wouldn't this be more of an array problem? As I understand it you can only interact with the top of a stack, not the elements below it.

  • @sanooosai
    @sanooosai Рік тому

    thank you sir

  • @CyberMew
    @CyberMew 2 роки тому +10

    We can also get rid of the tuple and just store the indices (without the values) in the stack, since it's already exist in the temperatures array and we can use it...

    • @VinodMoorkoth
      @VinodMoorkoth 2 роки тому +1

      Totally makes sense .

    • @thermalmedia6454
      @thermalmedia6454 2 роки тому

      Assuming that I understand this correctly, I think that this might not work with duplicate temperatures (finding the index of a temperature value will only return its first occurence).

    • @harigovind11
      @harigovind11 2 роки тому +1

      @@thermalmedia6454 No fetching from array using the index you can get the exact element.

    • @begenchorazgeldiyev5298
      @begenchorazgeldiyev5298 2 роки тому

      👏 Yeap, just what I was thinking. Then use the original array to get the temp at that index

    • @begenchorazgeldiyev5298
      @begenchorazgeldiyev5298 2 роки тому +1

      @@thermalmedia6454 No, we will get the temperature at the index we initially encountered it. Supposed you added index of 1 to the stack, when we get it from the stack either via peek() or pop(), and retrieve it from initial array temperatures[1], it will give us the temperature at that exact index.

  • @izzya8132
    @izzya8132 Рік тому +8

    I came up with this same O(n) solution, submitted it to Leetcode and got a Time Limit Exceeded error.
    Looked at my code for ten minutes, trying to figure out how I could possibly optimize it. Then I tried running the long input that broke my code, and it ran pretty fast so I thought "something is weird here", and just submitted the answer again. Got "faster than 86%"... Turns out my answer was fine the whole time, it was just lag or something on the first submission.
    I do appreciate Leetcode's problem set and how relevant it is to real interviews, but god I just hate how terribly inaccurate its speed testing is.

    • @MinhNguyen-lz1pg
      @MinhNguyen-lz1pg Рік тому +2

      same here, I was slightly confused

    • @charlesdarkwind
      @charlesdarkwind Рік тому +1

      Same, I get time exceeded like 75% o the time with the same solution

    • @johnwick2018
      @johnwick2018 Рік тому +1

      same here

    • @GoodLuck-dv2zu
      @GoodLuck-dv2zu Рік тому +1

      Same here, I was like what the fu*k??. How to optimize this when its already O(N)

  • @naimeimran3247
    @naimeimran3247 2 роки тому

    Thanks

  • @omeletter
    @omeletter Місяць тому

    What are like characteristics of a problem where monotonic stack is suitable?
    I haven’t solved a lot of problem using mono stack, and having hard time knowing when to use it…

  • @omridrori3286
    @omridrori3286 2 роки тому

    hey what is the run time you didnt tell in the video, and i dont know how to calculate it here because it is not like realy we pass time the array....

    • @o8XOX8o
      @o8XOX8o 2 роки тому +2

      Runtime is O(n) - you simply iterate over the list of 'n' temperatures. Each iteration you push an element onto a stack O(1), and do some number of pops from the stack. Since we push 'n' elements, even though each step we can pop a variable amount of elements, the total number of these pops can't exceed 'n', so on average it's a single pop per iteration.
      In the loop:
      Pop stack and assign - O(1) average
      Push stack - O(1)
      Loop: O(n)
      Overall: O(n)
      Memory is also O(n) since worst case we would have a stack containing 'n' elements. We would run into this case if our temperatures were continually decreasing. 10,9,8,7,6,5,4,3,2,1 at the end of the iterations, our stack would contain every element ('n' elements), and our array to return would be all 0 since the condition of increasing was never met.

  • @k_co_KristidharPandit
    @k_co_KristidharPandit 2 роки тому +2

    Nice 👍🏻

    • @k_co_KristidharPandit
      @k_co_KristidharPandit 2 роки тому

      Hey, how are you, I don’t know you though, but I like your efforts buddy 👍🏻😊

  • @ToastFrench24
    @ToastFrench24 Рік тому

    Could you cover #2104 sum of subarray ranges? Thanks :)

  • @n.h.son1902
    @n.h.son1902 Місяць тому

    Can someone explain to me why it's O(n) time complexity. Because we have one loop to iterate through all elements in the temperatures, and another loop on the stack? So my interpretation would be O(n^2) time in the worst case scenario. For example, if we have temperatures = [50, 49, 48, 47, 46, 45], then the stack = [[50, 0], [49, 1], [48, 2], [47, 3], [46, 4], [45, 5]]

  • @balagupta7132
    @balagupta7132 Рік тому

    Another version of next greater element problem!!!

  • @Sulerhy
    @Sulerhy 2 місяці тому

    I think there are not many people who can solve this problem in the first time without knowing about Monotonic Stack. Too hard.
    But this algorithm is so cool, worth to learn

    • @elitea6070
      @elitea6070 День тому

      I agree bro had no clue how to do it - at first I tried brute force but when I saw this video I was like "no way I was gonna think of this"

  • @ogsconnect1312
    @ogsconnect1312 2 роки тому +4

    Good job! and well done. I think the time complexity is still quadratic. Consider this example temperatures = [90, 80, 70, 60, 50, 40, 30, 100]

    • @BhanuPrakash-if2wl
      @BhanuPrakash-if2wl 2 роки тому

      it is not quadratic bcoz in your example we are traversing 2N times not N*N times(i too got confused about this)

    • @ogsconnect1312
      @ogsconnect1312 2 роки тому

      Thanks@@BhanuPrakash-if2wl As long as there is an inner while loop inside an outer for loop, the worst. case time complexity is quadratic. It will only be 2 * N, if you exited the first for loop, before starting the second while loop.

    • @NeetCode
      @NeetCode  2 роки тому +38

      Having an inner loop does not mean quadratic, that's a common mistake people make. You have to look at the context, the inner loop will never run more than N times total, so it can't be quadratic.

    • @shreshtashetty2985
      @shreshtashetty2985 2 роки тому +1

      @@NeetCode Then what exactly is the time and space complexity?

    • @harishsn4866
      @harishsn4866 2 роки тому +8

      @@shreshtashetty2985
      Time complexity is O(N) because each element can only be added to the stack once, which means the stack is limited to N pops. Every iteration of the while loop uses 1 pop, which means the while loop will not iterate more than N times in total, across all iterations of the for loop.
      This gives a time complexity of O(2N) =O(N).

  • @algorithmo134
    @algorithmo134 2 роки тому +3

    @NeetCode can you do 629. K Inverse Pairs Array? Im stuck for this question for the whole day? Please help me. 😭

    • @CEOofTheHood
      @CEOofTheHood 2 роки тому +1

      its a fucking hard question i just left it.

    • @algorithmo134
      @algorithmo134 2 роки тому

      @@CEOofTheHood @NeetCode help us

  • @vaibhavnakrani2983
    @vaibhavnakrani2983 6 місяців тому

    I cannot know how can this be O(n). For only increasing and only equal input temp it is O(n).
    However, when there are increasing and decreasing temps in the array it it not O(n).
    You can try putting a count variable inside both the loops and see.

  • @MIDNightPT4
    @MIDNightPT4 4 місяці тому

    10:17 I think you meant if our stack is not empty

  • @arunspal9166
    @arunspal9166 10 місяців тому

    i tried this with function...but it will run only for small number of arrays

  • @NikhilAsawadekar
    @NikhilAsawadekar Місяць тому

    Better approach:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    """
    Always try to find the next greater so easier to start from right hand side
    """
    stack = []
    n = len(temperatures)
    result = [0] * n
    for i in range(n-1, -1, -1):
    #while the existing temperature is greater keep popping until you find the greater temperature in top of the stack
    while stack and temperatures[stack[-1]]

  • @devanshsharma5159
    @devanshsharma5159 2 місяці тому

    I actually solved this using the sliding window but ended up failing test cases because it was too slow :| Using a monotonic stack is way easier.

  • @beeramrahulreddy11
    @beeramrahulreddy11 2 роки тому +7

    To me at first glance it looked like to find the next greater element on right for each element

    • @samuelhyeman7851
      @samuelhyeman7851 7 місяців тому

      same here. I used two pointers in my first attempt

  • @indhumathi5846
    @indhumathi5846 11 місяців тому

    understood

  • @XxM1G3xX
    @XxM1G3xX 3 місяці тому

    Hey guys, here is my solution.. easier to understand I would hope:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    res = [0] * len(temperatures)
    stack = []
    for i in range(len(temperatures)):
    while stack and temperatures[stack[-1]] < temperatures[i]:
    j = stack.pop()
    res[j] = i - j
    stack.append(i)
    return res

  • @oobleck147
    @oobleck147 Рік тому +1

    How is this not O(n^2) ?, there is still an inner while loop whose length is 'n'?

    • @minciNashu
      @minciNashu Рік тому +1

      actually it's O(n * 2), so O(n)

  • @satyamsinghal930
    @satyamsinghal930 Місяць тому

    instead of keeping holes in the output array, i created the monotonic stack traversing backwards. LOL. Stupid things stacks make you do

  • @iRYO400
    @iRYO400 Рік тому +1

    There is the 47th test case in LeetCode - where N = 10^5 and temperatures = [99,99,99,99,99...N-1, 100]. With this approach it exceeds time limit

  • @atomicbreath4360
    @atomicbreath4360 2 роки тому +2

    In worst case scenario the size of the stack will be 10^5 as n can be at the much. One alternate ways is to create a temp array of size 101 (as temperature cannot be more then 100) and when ever u want to find look at temp array starting from temperature [i+1] to 101. Time complexity is 0(100*n) but space will always remain constant more precise 0(100)

  • @_sf_editz1870
    @_sf_editz1870 4 місяці тому

    here the java code : class Solution {
    public int[] dailyTemperatures(int[] temp) {
    ArrayDeque stack = new ArrayDeque();
    int ans[] = new int[temp.length];
    // we need a strictly decreasing queue
    for(int i=0; i

  • @venkatalaxmimounikabatchu4591
    @venkatalaxmimounikabatchu4591 Рік тому +1

    here we are using while loop inside for loop, so how come the time time-complexity is linear?

  • @haolintang
    @haolintang 4 місяці тому

    class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    tempidx = {}
    for i, n in enumerate(temperatures):
    tempidx[n] = i
    stack = []
    res = [0] * len(temperatures)
    for i in range(len(temperatures)):
    while stack and stack[-1] < temperatures[i]:
    val = stack.pop()
    idx = tempidx[val]
    res[idx] = i - idx
    stack.append(temperatures[i])
    return res
    why this is wrong in some cases

    • @jst8922
      @jst8922 2 місяці тому

      There is an issue with the way the index of the value is calculated when updating the result (res) array.
      The index variable should be updated to the current index i instead of the index of the popped value from the stack.
      Here is the corrected code:
      class Solution:
      def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
      tempidx = {}
      for i, n in enumerate(temperatures):
      tempidx[n] = i
      stack = []
      res = [0] * len(temperatures)
      for i in range(len(temperatures)):
      while stack and temperatures[stack[-1]] < temperatures[i]:
      idx = stack.pop()
      res[idx] = i - idx
      stack.append(i)
      return res

    • @jst8922
      @jst8922 2 місяці тому

      ```python
      class Solution:
      def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
      tempidx = {}
      for i, n in enumerate(temperatures):
      tempidx[n] = i
      ```
      - The `Solution` class contains a method called `dailyTemperatures` that takes a list of temperatures as input and returns a list of integers.
      - The `tempidx` dictionary is initialized to store the index of each temperature in the `temperatures` list.
      - The `enumerate` function is used to iterate over the `temperatures` list, providing both the index `i` and the temperature `n` at each iteration.
      - The index `i` of each temperature `n` is stored in the `tempidx` dictionary with the temperature as the key.
      ```python
      stack = []
      res = [0] * len(temperatures)
      ```
      - An empty stack `stack` is initialized to keep track of the indices of temperatures.
      - The `res` list is initialized with zeros, having the same length as the `temperatures` list. It will store the number of days to wait for a warmer temperature.
      ```python
      for i in range(len(temperatures)):
      while stack and temperatures[stack[-1]] < temperatures[i]:
      idx = stack.pop()
      res[idx] = i - idx
      stack.append(i)
      ```
      - The code iterates over the indices of the `temperatures` list using a `for` loop.
      - Inside the loop, a `while` loop is used to check if the stack is not empty and the temperature at the top of the stack (index `stack[-1]`) is less than the current temperature `temperatures[i]`.
      - If the condition is true, it means a warmer temperature is found. The index `idx` at the top of the stack is popped, and the corresponding value in the `res` list at index `idx` is updated with the difference between the current index `i` and `idx`, representing the number of days to wait for a warmer temperature.
      - After the `while` loop, the current index `i` is appended to the stack.
      ```python
      return res
      ```
      - Finally, the method returns the `res` list, which contains the number of days to wait for a warmer temperature for each corresponding temperature in the input list.
      The code uses a stack to keep track of the indices of temperatures and efficiently finds the next warmer temperature for each temperature in the list. The time complexity of this solution is O(n), where n is the length of the `temperatures` list, as each temperature is pushed and popped from the stack at most once.

  • @edwardteach2
    @edwardteach2 2 роки тому +1

    U a God

  • @evlntnt1121
    @evlntnt1121 4 місяці тому +1

    Isn't it close to n^2 complexity in the worst case?

  • @deathbombs
    @deathbombs Рік тому

    Took me a while to see it, but once we do it's easy - not a fan of these trick questions where it's easy only if we solved it before.
    To me the solution is a stack that tracks the smallest value. If we come across a larger value, we keep popping from the stack. This works because values that work for larger values will also work for the smallest values on the top of stack.

  • @Beverage21
    @Beverage21 Місяць тому +2

    wow i used to think that you explain things nicely but damn this is confusing. no offence

  • @lakewobegonesbest8725
    @lakewobegonesbest8725 9 місяців тому

    Excuse me sir but 69 is always greater. Sorry, I can’t help myself.

  • @sonysherpa3184
    @sonysherpa3184 Місяць тому

    incase anyone is having difficulty understanding this. I found this video easier to understand.
    ua-cam.com/video/ekFs9Nb2RNQ/v-deo.html

  • @ianokay
    @ianokay 8 місяців тому

    8:09 You talk about popping the stack but are still using the popped values to be present to indicate distance (for the number 75 in your example). Popping doesn't allow for that as it shortens arrays, so this explanation doesn't make much sense.
    Also popping occurs from the end, shifting occurs from the beginning, and you're referring to "popping" numbers with earlier index values (inserted earlier) with items inserted later at the end, which also doesn't make sense at face value (you're placing the number in your stack in your explanation and then discussing popping earlier values).
    **EDIT** This only makes sense when you get to the code section and realize you're storing the index in the value. It makes no sense (as I commented above) to a first-time observer watching your drawn explanation.

  • @vulcs
    @vulcs Рік тому

    why you speak so fast

  • @Ryan-sd6os
    @Ryan-sd6os Рік тому

    slow down mate