Sum of Subarray Minimums - Leetcode 907 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 5 ก.ย. 2024

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

  • @ayushman_sr
    @ayushman_sr 5 หลายเดือนก่อน +57

    Raise hand if you still didn't understood it by now 🤚

  • @theruler1096
    @theruler1096 7 หลายเดือนก่อน +114

    If you face interview question like this, you're not unlucky. You're just dead.

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

      Sorry a noob here... how bad is it to solve it with O(n^2) on an interview?

    • @anti-tankartur677
      @anti-tankartur677 7 หลายเดือนก่อน +6

      ​@@tryundel you're basically showing that you have a grasp on the basics but you're not good enough to optimize solutions. For prestigious companies, I think it's generally perceived as red flag.

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

      @@tryundel The obvious brute force approach is n^2 so you will need to come up with a O(n) solution. The interview is at least 45 mins and if it's just 1 question, after you provide the brute foce, you will be expected to come up with the optimal solution

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

      you will not be moving forward to next step, even it is an internship position (my experience with one of the FAANG)@@tryundel

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

      what we call "your village people" over here

  • @davi_singh
    @davi_singh 7 หลายเดือนก่อน +54

    Everytime I think I have a handle on leetcode, I get a question like this one and I wonder why the heck am I so dump. Thanks @NeetCodeIO you have the best explanations

    • @abrahamlincoln5724
      @abrahamlincoln5724 7 หลายเดือนก่อน +1

      Same reason why I hesitate to apply to jobs in big tech where LC questions are common. How do you solve a question if you never encountered similar question(or pattern) before?

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

      @@abrahamlincoln5724 same boat brother, I am shit scared cause of the same thing. Have been grinding LC for 3 months gone through 4 study plans but don't feel ready at all

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

      @@abrahamlincoln5724 you practice enough problems so that its unlikely to be a new pattern

  • @ryo_dm
    @ryo_dm 7 หลายเดือนก่อน +23

    If an interviewer decides to ask you this question, you are already rejected

  • @reckyru
    @reckyru 7 หลายเดือนก่อน +25

    Disgustingly hard problem IMO

  • @elyababakova2125
    @elyababakova2125 7 หลายเดือนก่อน +19

    crazy question

  • @hengyulee4319
    @hengyulee4319 7 หลายเดือนก่อน +8

    For the modified code, because when calculating left and right we are computing the distance of two elements and appending/prepending does not affect the distance. Two -inf solve some edge cases and empty the stack (except for the first -inf) in the last iteration of the for loop. Correct me if I am wrong.

  • @coolgamertm4411
    @coolgamertm4411 7 หลายเดือนก่อน +8

    Secret POV : Leetcode daily hard problem help this channel grow more

  • @m.varunreddy7365
    @m.varunreddy7365 7 หลายเดือนก่อน +9

    couldnt understand, this q is definitely not medium

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

    you could also add -inf only to the back off the arr,
    this absolute minimum will purge the stack without involving extra code at the end of the algorithm

  • @codingoak4701
    @codingoak4701 7 หลายเดือนก่อน +1

    The reason that optimization works is, for all the small values that dont get removed from the stack, the result will be dynamically updated for the distance to the ends of the array.

  • @rohitudamale4091
    @rohitudamale4091 23 ชั่วโมงที่ผ่านมา

    Good Explanation!!

  • @36saurabh
    @36saurabh 7 วันที่ผ่านมา

    Around 14:13, if I understand it correctly, does left always evaluate to 1 on line 10? Correct me if I'm wrong. Since all the elements in the stack before the popped element m at index j will be less than m, hence number of subarrays with m as the smallest element on the left of m will always be 1? Is this correct?

  • @vaishnavejp9247
    @vaishnavejp9247 7 วันที่ผ่านมา

    i had the understanding that monotonic stacks come in handy for problems like NGE because we dont just want to keep track of minimum element youve seen, but how close it is to the current element.
    that is, the closeness matters as well. but for problems like this, i dont understand why a monotonic stack is even needed? cant i just keep track of the minimum most element seen so far? this and trapping rainwater problem as well. someone pls explain why a stack is needed instead of just using mini pointer

  • @alxolr
    @alxolr 7 หลายเดือนก่อน +5

    Gosh if you get one of this during an interview you are done.

  • @sankalppatil2994
    @sankalppatil2994 7 หลายเดือนก่อน +4

    Rip I still dont get it

    • @sproutboot
      @sproutboot 7 หลายเดือนก่อน +1

      Same

  • @arunrajput1007
    @arunrajput1007 6 หลายเดือนก่อน +1

    hey @NeetcodeIO i am not sure for any new medium level problem i would be able to come up with a solution in 25 mins and this includes explanation + logic + coding + edgecases + dry run. This is not possible if one has already solved this question before.
    Just need your thoughts whether this is possible for everyone.

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

    for the second for loop, when you iterate over a stack. are you iterating it like an array? it seems that you assume you can iterate from the earliest added element all the way to the last added element, which is a queue not a stack. in stack you can only iterate over it via the last added element no?

  • @coffeebytes3257
    @coffeebytes3257 7 หลายเดือนก่อน +5

    💀 why cant my brain figure this stuff out without help 😭

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

      more practice more practice we got this

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

    I am wondering for n elements the total combination would be n square. Should it be multiple 2 n times and minus 1? Taking an example: n = 2, there are 3 combo, n =3: there are 7.

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

    I just solved this and the video uploaded 😅. Still watching tho, I like your explanation

  • @sk_4142
    @sk_4142 7 หลายเดือนก่อน +1

    A humbling problem indeed

  • @chien-yuyeh9386
    @chien-yuyeh9386 7 หลายเดือนก่อน +1

    Thanks for the amazing video

  • @chiragsrivastava4217
    @chiragsrivastava4217 7 หลายเดือนก่อน +1

    class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
    MOD=10**9+7
    stack=[-1]
    res=0
    arr.append(0)
    for i,val in enumerate(arr):
    while stack and val

  • @XEQUTE
    @XEQUTE 7 หลายเดือนก่อน +1

    wohoo , you did it!!
    ( hello from yesterday)

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

    Hello i have been following you since really long , I usually understand what you teach, but this video was a bit complex for me. But I have done this question.
    Here's my Python code.
    Its the same approach as yours, just more simple and brute forced.
    class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
    arr = [float('-inf')] + arr + [float('-inf')]
    previousSmaller = {}
    preStack = []
    nextStack = []
    nextSmaller = {} #hashmap
    result = 0
    MOD = 10 ** 9 + 7
    for i in range(len(arr) - 1, -1, -1):
    while preStack and preStack[-1][1] > arr[i]:
    j, m = preStack.pop()
    previousSmaller[j] = i #prev smaller element
    preStack.append((i, arr[i]))

    for i in range(len(arr)):
    while nextStack and nextStack[-1][1] >= arr[i]:
    j, m = nextStack.pop()
    nextSmaller[j] = i
    nextStack.append((i, arr[i]))
    for i in range(1,len(arr) - 1):
    minTimes = (i - previousSmaller[i]) * (nextSmaller[i] - i) #number of subarrays for which the element at index i is the minimum
    result += arr[i] * minTimes
    result = result % MOD
    return result
    # arr - 0 3 4 5 6 1 4 6 7 0
    # index - 0 1 2 3 4 5 6 7 8 9
    #for handling duplicates,we do >= while calculating for nextSmaller and > in prevSmaller
    #vice versa will also work

  • @SickleM
    @SickleM 7 หลายเดือนก่อน +1

    Can't believe I did this in first try!

  • @user-pq8mz5eb5w
    @user-pq8mz5eb5w 7 หลายเดือนก่อน +6

    there are n(n+1)/2 sub arrays not n²

    • @kartikhegde533
      @kartikhegde533 7 หลายเดือนก่อน +1

      he probably mentioned about overall complexity. which is still n^2

  • @user-vu4ng4rb8k
    @user-vu4ng4rb8k 7 หลายเดือนก่อน

    could you also upload videos for leetcode biweekly contests

  • @soumithjavvaji3310
    @soumithjavvaji3310 2 หลายเดือนก่อน

    Either getting rejected or giving a O(n^2) solution is predefined , if the interviewer asks this!

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

    Could this be solved with Segment Tree ?

  • @shellingford5534
    @shellingford5534 7 หลายเดือนก่อน +1

    I still don't understand why we are doing j + 1 in the else portion. Can someone please explain this to me like I am 5...

    • @anti-tankartur677
      @anti-tankartur677 7 หลายเดือนก่อน +2

      Basically, else is only done when the stack is empty. If the stack is empty after popping the last element, that means it is the smallest number in that array upto THAT index, which means that it is going yo be present in every subarray and will also be the minimum of all these subarrays. For example, suppose the stack is empty and the element popped is 1 at the index of 2. At index 0 and 1, you have 3 and 2. So for all the subarrays from the index 0 to 2, 1 is going to be the minimum nunber and hence j+1 (2+1 =3 ) as 3 subarrays will have the minimum as 1. Hope this helps.

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

      Let's say we have:
      nums = [2, 3, 5, 1]
      index = [0, 1, 2, 3]
      Let's say we are currently at index 3 (value = 1). Our stack (index, value) is:
      stack = [(0,2), (1,3), (2,5)]
      Since 1 is less than all of the values in the stack, we pop everything from the stack. When we get to (0,2), the top of the stack, the right count is 3. For the left count, since the stack is now empty, there is only a single value from the beginning of the array till this point, which is 2. Its index is 0, hence we need to add 1 to the index to get the count of subarrays from the beginning up to and including 2

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

      + 1 is include the jth element itself if the stack is empty is 0 + 1(itself) = 1

    • @JosephMuturi-j4d
      @JosephMuturi-j4d 2 หลายเดือนก่อน

      @@anti-tankartur677 This is an amazing explanation,,,,,only few can understand how figuring that out almost solves the problem,,,even neetcode couldn't explain that one,,,,it's genius

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

    but total number of subarrays is n*(n+1)/2 instead of n^2.

    • @harshitsharma2639
      @harshitsharma2639 2 หลายเดือนก่อน

      thats order n^2 tho

    • @jamjam3448
      @jamjam3448 2 หลายเดือนก่อน

      @@harshitsharma2639 You're talking of complexity, not the number of subarrays. They are different

    • @harshitsharma2639
      @harshitsharma2639 2 หลายเดือนก่อน +1

      @@jamjam3448 i know that dude. The time to traverse and build the result will still be O(n^2) thats what neet was trying to say.

    • @jamjam3448
      @jamjam3448 2 หลายเดือนก่อน +1

      @@harshitsharma2639 yeah i think that's what he was trying to say also but he kept saying number of times instead of the time complexity as the two are different.

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

    class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
    mod=10**9+7
    n=len(arr)
    @lru_cache(maxsize=None)
    def solve(i, n, mn):
    if i == n:
    return 0
    curr = arr[i]
    if curr < mn:
    mn = curr
    return (mn + solve(i + 1, n, mn)) % mod
    sumTotal = 0
    for i in range(len(arr)):
    sumTotal = (sumTotal + solve(i, len(arr), inf)) % mod
    return sumTotal. Hi Neetcode I wrote this recursive approach and it passes 82/87 test cases, and then fails with memory limit exceeded error, I was wondering it this question is only possible via iterative approach?

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

      every iterative code can be done recursively, i would suggest trying to implement tail recursion because python optimizes it for memory

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

      Doesnt make a differnce if recursive stack overflows@@CrabGuyy

  • @upendrakumar-bw1jd
    @upendrakumar-bw1jd 4 หลายเดือนก่อน

    Actually i am big fan of neetcode because he is the only one who gives better intitution but this time really want to say this time neetcode fail to explains this problem

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

    Hard one

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

    i was waiting thx

  • @haoli8983
    @haoli8983 2 หลายเดือนก่อน

    this question is so hard == why just medium ?

  • @s016_aviratshambharkar2
    @s016_aviratshambharkar2 7 หลายเดือนก่อน +2

    Subarrays should be n (n + 1) / 2 right ??

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

    Stack grows upward, but I get the point

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

    I didn't understand anything related to the use of stack in the code 😶‍🌫

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

    It's too complexity for me, though I have solved 243 questions.

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

    hey man , its time for u to answer here why u did that

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

    can you explain the last code

    • @vinsin4619
      @vinsin4619 7 หลายเดือนก่อน +1

      the negative inf added to front and back of the array

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

      The neg inf at the back ensures that the elements in the monotonic increasing stack are processed, as everything inside is smaller than neg inf (same as the original loop over the stack).@@vinsin4619

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

    This question made me question Leetcode smh
    Did you solve it on your own

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

    how can I continue watching this video, when 1 min in you are giving wrong explaination.... no. of subarrays are not n^2 its n(n+1)/2

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

      its O(n ^ 2) . n * (n + 1) /2 is still O (n ^ 2)

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

      Ohh, sry for the wrong explanation, I am not talking about time complexity..
      He said no. of subarrays is array are n^2..but no of subarrays are n(n+1)/2

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

    i understood nothing

  • @ehm-wg8pd
    @ehm-wg8pd 2 หลายเดือนก่อน

    if you get this interview question, omaewa mou shindeiru

  • @pastori2672
    @pastori2672 7 หลายเดือนก่อน +1

    too much intuition

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

    😭👍

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

    Def hard not med

  • @johnthompson1327
    @johnthompson1327 7 หลายเดือนก่อน +1

    first

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

    checking solution in Python is useless for understanding, when iterating ur iterating from top of stock to bottom or reverse.
    Python is such a sloppy choice of language for DSA

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

    still dont get it