Subarray Sum Equals K - Prefix Sums - Leetcode 560 - Python

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

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

  • @beeramrahulreddy11
    @beeramrahulreddy11 3 года назад +433

    u forgot to add 2,1 to the hashmap

    • @TobiasWheaton
      @TobiasWheaton 3 года назад +11

      Good catch, i was thinking about that too bc its easier to see the pattern if its consistent on when u add (even if its not needed for this example)

    • @prasad9012
      @prasad9012 2 года назад +35

      I just spent like 10 minutes rewinding and forwarding the video trying to understand why 2 wasn't added. Thankfully, I found your comment now.

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

      Actually, it is just not {2:1}. He forgot to add the current sum to the hash table when it is not found in the table.

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

      Yup .. I was also thinking about that ..

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

      haha yeep. my OCD went brrrr... I was like wheres the 2 :P ..

  • @suvajitchakrabarty
    @suvajitchakrabarty 7 месяцев назад +55

    If you are having difficulty understanding this or wrapping your head around the solution, maybe this might be a good way to think about it. The question asks how many subarray sum equals to k. For a subarray to sum to k, you need a subarray, as in a part of the array from index 'a' to index 'b' to have a sum equal to k. But when we reach any index 'b', we obviously do not know, if there was a subarray from index 'a' to index 'b' equal to k. However we do have the sums from 0 to index 'a' in our hash map, because we have been storing all sums starting from index '0' to every single index till now, and the count of them as the value of the key. Now obviously sum_0_to_a + sum_a_to_b = total sum so far (curSum). If we go to the original ask, which is we need a prefix that is sum_a_to_b to be equal to k. For that to hold true, replace sum_a_to_b with 'k'. Hence, sum_0_to_a + k = curSum. Hence curSum - k = sum_0_to_a. And then since we have been storing all possible values of sum_0_to_a so far in the hashmap, curSum - k must exist in the hashmap as a key, and we can simply add the value from the hashmap to add number of prefixes from 0 to any index which equalled to curSum - k .

  • @Question418
    @Question418 3 года назад +132

    I like your attempt to explain it, even though I don't fully understand it. I appreciate it.

  • @kimstuart7989
    @kimstuart7989 Год назад +108

    You know I remember first learning CompSci, I thought the specific algorithm concepts (BFS, DFS, Dijkstra, etc.) were the hard ones to learn. Now that I am more experiences, I realize that the what I thought then were 'basic' data structures, i.e. arrays, strings, etc. are actually the harder ones to make sure you understand because those concepts has many dedicated algorithms to them, such as Kadane, prefix/suffix array, KMP etc. that you need to know to truly understand that data structure. So while I glossed over arrays because I knew their functions, I am now revisiting to make sure I understand the algorithms embedded in them. Learning truly never does stop!

    • @fatcat22able
      @fatcat22able Год назад +15

      Honestly same here. I figured that arrays would be relatively simple, and they are simple on the surface, but there are so many algorithms and different types of problems that involve them that it feels like they're an entire rabbit hole unto themselves.

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

      Facts man

    • @davidnwaekwu9019
      @davidnwaekwu9019 17 дней назад

      factssss, at a point i thought smth is wrong with the way i think .

  • @ObaidullahGhawsi
    @ObaidullahGhawsi 3 года назад +82

    Thanks, NeetCode for these solutions and explanations, It would be really helpful to make a video about general techniques that you use to solve these problems... Because we wan to know how to approcah these kinds of problems by ourselves. Thanks again.

  • @mangalegends
    @mangalegends Год назад +19

    I'm still trying to wrap my head around this
    EDIT: Came back a few weeks later and it makes 100% sense to me now

  • @ngndnd
    @ngndnd 10 месяцев назад +3

    i think im just dumb af bc i still dont understand it

  • @josembass
    @josembass 2 года назад +64

    Great explanation.
    How are we supposed to come up with a solution like this in 30m without having seen it before!

    • @darshana5254
      @darshana5254 2 года назад +25

      We cannot. These are classic problems asked during interviews. Whoever come across this problem would easily solve it. Other would go with bruteforce approach which doesn't work on interviews.

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

      @@darshana5254 thanks bro, you’ve raised a very important point. Only if one has encountered such problems, only then will he be able to solve the problem cuz he knows how to optimum approach.

    • @mobaisi13
      @mobaisi13 2 года назад +27

      That's the neat part. You don't.

    • @vineethsai1575
      @vineethsai1575 2 года назад +48

      I got this question in the interview and I did not know the optimal solution. However I was able to produce the n^2 solution quickly and the interviewer started giving me hints to use Hashmap to reduce it to O(N). I scrambled here and there but was able to talk about the "repeated work" being done and how I could use hashmap to save the work. In the end I was not able to code it up. Interviewer still passed me though.

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

      @@vineethsai1575 what company

  • @scottloewke5199
    @scottloewke5199 2 года назад +40

    Good explanation and, fortunately, the omission of the [key = 2, count = 1] map entry did not affect the result. However, it would be good if NeetCode could add text at that part in the video to make it clear what happened.

    • @AndreiSokolov-k7j
      @AndreiSokolov-k7j 7 месяцев назад +2

      It's not about a bug in the code, it's about a bug in the video. 9:55 Here you should have added key 2 and value 1 to the hashmap and that's it.

  • @darkwhite2247
    @darkwhite2247 8 месяцев назад +5

    08:21 - i have no idea how we are supposed to figure out during the coding interview that (0,1) has to be added into the hashmap by default. How is anyone solving this without memorizing during interviews? May be i'm dumb to not understand this even though the instructor is explaining it. Please help me understand the intution behind adding (0,1) in hashmap by default.

    • @AndreiSokolov-k7j
      @AndreiSokolov-k7j 7 месяцев назад

      bcs if you find that n-k = 0 means that you dont need to remove anything so basically it be 0, 1 by default

  • @apoorvwatsky
    @apoorvwatsky 2 года назад +15

    1:55 I needed to hear that, I wanted to know why sliding window won't guarantee correct answer for these constraints. That cleared it up.

  • @CliffordFajardo
    @CliffordFajardo 3 года назад +30

    Initially I thought it was a sliding window problem, Trying to wrap my head around this ...patience, time...ahhh. Thanks for the video!

    • @ziomalZparafii
      @ziomalZparafii Год назад +8

      I thought about it as a sliding window problem until I found out there can be negative values. If we would only have positive ones, you would increment right pointer while sum is less than k, then increment left while sume is more than k. That would be my approach (not tested).

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

      @@ziomalZparafii the main problem behind sliding window approach is some edge cases. For example: [1,-1,0], k = 0
      If we will use two pointers approach (or dynamic sliding window), then we will return 2 instead of 3.
      1) sum=1, count=0, left=0, right=0
      2) sum=0, count=1, left=1, right=1
      3) sum=0, count=2, left=2, right=2

    • @ziomalZparafii
      @ziomalZparafii Год назад +4

      @@aleksandr_t you have a negative value in your array. Read my comment once again :-)

    • @matom2473
      @matom2473 6 месяцев назад +2

      in a real interview we can not make this mistake, it will take you 20 mins to find out sliding window will not work

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

      @@ziomalZparafii you still can use a sliding window with negative numbers, it depends on requirements and edge cases, so your first comment is not entirely accurate.

  • @timzhang6651
    @timzhang6651 3 года назад +31

    Well explained, and it takes effort to make a video as good as this. Thank you!

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

    00:40 The brute force approach is O(n^3), not O(n^2). There are ~n^2 subarrays but summing a subarray is O(n).

  • @thndesmondsaid
    @thndesmondsaid Месяц назад +1

    the idea that we're expected to come up with this solution on the fly in an interview is bonkers to me

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

    Just failed this one in an interview. I just don't get it even when with such detailed explanation

  • @kalp2586
    @kalp2586 4 месяца назад +1

    Yeah it's complicated but don't forget to come up with the optimal solution in 10 minutes without any compiler errors and of course it needs to pass all test cases in the interview. smh. Tech interviewing has become a circus.

  • @tempregex8520
    @tempregex8520 2 года назад +17

    i appreciated you explaining this. But, it would have been more helpful(esp to people like me) where you would have taken the time to explain more about the use of HashMap for maintaining prefixSum -> Count to me it felt like the explanation went "too fast" as soon as you discussed the brute force solution.But, in any case a great attempt indeed.

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

    This is a LC hard imo, gawd damn!

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

      Agree, it's definitely more difficult than some actual hard problems.

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

    Why did you initialised your dictionary before hand with (0:1)

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

    Wayyyy less confusing than the explanation on leetcode

  • @itspete2444
    @itspete2444 6 месяцев назад +1

    Why are array and string problems 10x harder than graph, matrix and dp???

    • @kaushik.aryan04
      @kaushik.aryan04 6 месяцев назад

      yeah atleast graph matrix dp follow a single type of questions these are like so different from each other

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

    A slightly cleaner solution using a defaultdict
    class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
    prefixSums = defaultdict(int, { 0 : 1 })
    curSum = 0
    res = 0
    for n in nums:
    curSum += n
    res += prefixSums[curSum - k]
    prefixSums[curSum] += 1
    return res

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

    Crazy good explanation. Subscribed. Thank you man !

  • @user-wx8hn3ng6b
    @user-wx8hn3ng6b 4 дня назад

    It's a good combination of two sum and prefix sum.
    And the intuition should be:
    1. subarray sum -> prefix
    2. equals k -> two sum
    The only difference is it's 'b - a = k' instead of 'b + a = k', and you just need to calculate the 'a' differently.

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

    i still dont get it, im dumb

  • @unwarysage05w32
    @unwarysage05w32 Год назад +3

    This is a way better explanation than leetcode premium’s explanation thank you!

  • @Retrosenescent
    @Retrosenescent 2 года назад +9

    You explained it so perfectly that I didn't even need to see the code to be able to code it myself :) thank you!!

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

    so what you are saying is we have a map that shows how many ways we can come up with given sum so for sum 0 we can come up with 2 sequences, but these sequences have to be contiguous , how to prove that 0 has 2 only if we pop up contiguous elements from current sum ?

  • @quirkyquester
    @quirkyquester 7 дней назад

    just gotta keep practicing! Thank you Neetcode for making all these amazing videos!

  • @lovipilowu9766
    @lovipilowu9766 4 месяца назад

    How are you supposed to figure this out in 30 minutes? I watched this three times and didn't look at the code at the end, I was able to figure it out and code it quickly once understanding what you're supposed to do, but I couldn't figure it out at all during an interview once I realized there could be negative numbers. Why would having negative numbers not just twist the problem up a bit, but ENTIRELY change the approach and fundamental way to solve it? Ridiculous.

  • @a2m2tkyo
    @a2m2tkyo 25 дней назад

    I don't understand why you kept Prefix Sum of 0 and count 1 when you started over and changed the index 1 element from 1 to -1. It's a new example, why did you not reset the hash table?

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

    Do you know what's the drawback of your videos are? You take plenty of time just to explain why 2+2 = 4, I mean just explaining the basics of the logic to think of and same logic in many examples, repeating the same line to expand the length of video. While explaining how to write that logic in any computer language you are using, BOOM, in just a few seconds. I think maximum of the viewers search the explanation to understand how to write or explain the software to do that, not just the logic. Please think of that.

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

    Another way to think about why we would set our key value to {0:1} instead of memorizing, is to think what if that single element, itself is the target.
    For example:
    input = [1, 1, 4] , k = 4
    occur = { 0: 1 }
    By just eyeballing, you'll see the output is 1, since the last element is a 4. When we iterate through the input, we'll do input[2] - k (4 - 4) = 0. Do we have a 0 in our hashmap/dictionary? Yes we do, it's value is 1.

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

      except in this scenario wouldn't we be doing currSum - k (6 - 2) = 2, and we would be looking up the value for 2 in our hash map, which would be 1. I think your scenario only works if the single element that is the target is the first element in the input.

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

    just wow!!

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

    Why doesn't sliding window approach fails here:
    - Assumption: adding an element to increase and removing an element to decrease any sum is valid only if all elements are non-negative.
    - removing negative elements increases total sum and vice versa, hence breaks tests containing negative number
    - not suitable approach for this problem

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

    No way anyone can come up with this in an interview

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

    get() is unnecessary can just add to hashmap regularly. this drawing analysis is goated though!!!

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

    too many unnecessary words, people who practice this is smart enough to understand with just a 1 minute video recap

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

    10:02 Why didn't we add 2 as a prefix there? Was that a mistake on your part? I'm confused.

  • @KernellNinja
    @KernellNinja 2 дня назад

    I think using Kadane’s algorithm it should be simple

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

    How does this solution prevent subarrays that sum up to k from being counted more than once? I don't get it.

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

    what a great explanation , saw many videos, amazing explanation of intuition.

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

    Whats wrong with this recursion code ??
    int solve(vector& nums, int k, int n, int curr) {
    if(n==0) return 0;
    int res=0;
    curr+=nums[n-1];
    if(curr==k) {
    res++;
    } else {
    res+=solve(nums, k, n-1, curr);
    }
    res+=solve(nums, k, n-1, 0);
    return res;
    }

    int subarraySum(vector& nums, int k) {
    int n=nums.size();
    return solve(nums, k, n, curr);
    }

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

    Is it just me that did not get anything? Prefix sum is very hard to understand even if we see the solution. Coming to a solution for entire new question in an interview is very difficult.

  • @roman-berezkin
    @roman-berezkin 22 дня назад

    Absolutely love this guy, not lessons but a masterpiece!

  • @johnsmith-bk5ph
    @johnsmith-bk5ph Год назад

    Still dont get how to arrive at using a map, no intuition
    This is a crappy problem

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

    damn this question is much harder than i thought
    thank you for the explanation tho

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

    What a god of prefix sums. Great vid!

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

    I feel bad for watching solutions, but I don't know what else to do

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

    Can it be considered as a dynamic programming solution?

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

    By far the best explanation to this problem

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

    you say "right" waaaaay too much; it's pretty distracting

  • @AliMalik-yt5ex
    @AliMalik-yt5ex Год назад

    I'm even more confused than I was before I saw this video.

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

    Just wonder why the prefix sum 2 is not in the hashmap.

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

    Hi @NeetCode. I am not able to understand the part where you say. we need to add the prefix sum to Hashmap simultaneously. even if are maintaining the Hashmap first. we can still get count of prefix - k and prefix = k.

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

      Take this example: [1]; k = 0. Without adding first your prefix sum array would be: 0->1 and 1->1. Now you will compute prefixSum-k for each key. 0 - 0 = 0, You say you have a match(which is just the empty prefix). Now you compute 1- 0 = 1, you check your map and the value exists, so you return a count of 2. That is why the update needs to happen simultaneously. So, that you can check the subarray between some starting index "i" and current index "k"(excluding k). Hope this makes sense.

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

    I don't understand why line 12 is necessary

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

    It's easier to use defaultdict instead of the .get

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

    but how do you know the difference will be contigous with the current sum ?

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

      Because you substract a prefix, you don't select element in your window

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

    Your channel is really underrated man 😢

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

    This reminds me of the two sum solution.

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

    I wrote a dp and find out that same as brute force ...

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

    Bless you, O savior from heavens above!!

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

    Godlike explanation to a looked easy problem. Hats off my man

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

    this is the first neetcode, i didn''t understand XD

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

    this question not in you 150 problem set?

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

    Not clear bro. Delete my comment now

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

    No way I can get the solution in interview

  • @cfbf96
    @cfbf96 4 месяца назад

    im so dumb, never gonna get this.

  • @servantofthelord8147
    @servantofthelord8147 17 дней назад

    This is a valuable problem.

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

    I see some confusion on why we initialize prefixSum = {0:1}, and that's because we can always produce 0 by taking no elements from our array (e.g. []). This works out nicely when we run into a subarray that has a sum == k, because sum - k = 0. Then the question we ask at this moment is "is there a prefix-subarray I can take away from my current subarray sum that also equals 0?" The answer is yes, because I can takeaway no elements from my current subarray and the current subarray sum will still equal k.

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

    is this question on neetcode? i cant locate it

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

    Awesome explanation❤️
    Can you plz solve
    Count submatrices with all ones?

  • @Adam-tz6gk
    @Adam-tz6gk 23 дня назад

    This is by far the best explanation in the web for this problem, thank you so much NeetCode!

  • @arifinrahman6
    @arifinrahman6 10 дней назад

    amazing explanation :)

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

    I was actually asked this question for a Facebook internship position in 2019.

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

      Did you find the optimal solution in an interview? Had you seen this problem before? If no, did you pass that round?

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

    What is the name of this algorithm?

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

    There is another edge case for adding 0->1in the starting , which is if the. nums[0] is 0. This intuition is quite tricky but great explanation.

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

    I have a doubt. If the array is 6,4,3 and k is 9. we find that sum till n is 13 and 13-k ie 13-9=4 is present in the array so that will get counted but in reality it is wrong as it is not a subarray is we dont pick contiguous element. please explain

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

    great solution thank you

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

    Really good explanation. Thanks.

  • @uzzwalpreetkaur3374
    @uzzwalpreetkaur3374 4 месяца назад

    I understood this explanation! Thanks!! I was trying with sliding window technique first and getting the wrong answer until I realised that we can have negative numbers. This is indeed is a neat.

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

    Never been more lost in my life

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

    This guy is Goated 🚀

  • @david-nb5ug
    @david-nb5ug 7 месяцев назад

    this should be a hard T.T

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

    I don't know why it works, but still works! ;)
    Everytime I have to revisit the solution before interview. ;(

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

    Do the next harder version of this which is Continuous Subarray Sum 523

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

    I am not sure, but take an example where the array is [-1,1,-1] and k>0(e.g., 2). The result would be 1, since after the 1 is covered, and then we went into the -1 again, the result will be 1, and that's not true (should be 0). Am I missing something?
    I think the results should be added only if the cursum is >=k

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

    amazing explanation!!

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

    Oh man its a brain gym ...

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

    I have watched at least 50 of your videos and this is the only one I found difficult to understand. Nevertheless, thank you for your content.

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

    Delete my new comment

  • @amrsanu
    @amrsanu 9 месяцев назад +1

    Bawal item ho Yaar. 👌Hats off 🫡

  • @ET-Programming
    @ET-Programming 11 месяцев назад

    not clear explanation

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

    Did this problem but used an array to keep track of the running totals then reversed it... used a deque after but wow is deque slow and memory intensive

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

    Mind = blown.

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

    nice explaination

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

    thank you man!!

  • @Alexis-ym9ph
    @Alexis-ym9ph Год назад

    How feasible would it be to solve this kind of problem at the interview, given you never seen the solution before?

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

    Very informative man. Keep up the good work.