Continuous Subarray Sum - Leetcode 523 - Python

  Рет қаралды 77,109

NeetCode

NeetCode

Күн бұрын

Пікірлер: 136
@mdazharuddin4684
@mdazharuddin4684 2 жыл бұрын
We add {0 : -1} in dict not to handle case where 1st element is divisible by k. We add it to handle case where subarray starting from 0 is divisible by k. For example when k = 6 and nums = [1,2,3,4] and we don't initialize 0, we will get False.
@xinl9259
@xinl9259 2 жыл бұрын
Thanks! I watched the video and could not understand why {0:-1} and you answered my question. Very appreciate!
@shin-wu
@shin-wu 2 жыл бұрын
Great addition to the video! Thanks for the clarification.
@halahmilksheikh
@halahmilksheikh 2 жыл бұрын
Yep. Also a way to get rid of that is to have `if (remainder == 0 && i > 0) return true` in the for loop
@a_maxed_out_handle_of_30_chars
@a_maxed_out_handle_of_30_chars Жыл бұрын
yeah, this makes sense
@AbhishekMakwana-p1v
@AbhishekMakwana-p1v Жыл бұрын
you Can Just Add this Condition if sum%k==0 and i>=1: return True
@khanofkhans4832
@khanofkhans4832 2 жыл бұрын
Continuous Subarray Sum of PAIN
@Ginger_Hrn
@Ginger_Hrn 4 ай бұрын
in the arse
@ObtecularPk
@ObtecularPk 2 жыл бұрын
Again, how is someone able to come up with a solution like this in a time limit interview? This is the question that needs answering next video or something
@easynow6599
@easynow6599 2 жыл бұрын
i am thinking the same..in most of these problems..I guess there are three ways: a) you should know the problem beforehand and solve it..so it would be relatively easy to repeat during interview..b) you get plenty of help from the interviewer and you kinda solve it with bugs or/and pseudocode..c) you have spend your life with LC and you solve it in 15' seeing first time.. I dont see myself even close to option c and i guess i have to practice 10 times more..but i would be curious if someone who has passed the interview can tell
@halahmilksheikh
@halahmilksheikh 2 жыл бұрын
Step 1: Solve it before the interview Step 2: Solve it during the interview and pretend you've never seen it
@rams2478
@rams2478 2 жыл бұрын
I second that... looks interview is pure luck...
@josecabrera7947
@josecabrera7947 2 жыл бұрын
@@easynow6599 I had an interview with a big tech company like last week. I was able to solve roughly 2 problems that I had never seen before that I would categorize as leetcode easy's. They had edge cases that took time and killed like 35 min. The other two however one was hard and the other was either hard or medium. I had no idea how to solve them. I was able to get some work in but couldnt pass all the cases. I later looked them up for hours and was able to find 1 similar but not entirely the same. I spent like 2 hours trying to understand and solve the problem I found. There is no way someone can solve these in 15 minutes.
@easynow6599
@easynow6599 2 жыл бұрын
@@josecabrera7947 i dont know man..this leetcode looks like a BS system.. but discussing about that i think it's the optimal way to filter people..with a lot of false negatives (a lot of good people stay out because a problem was too hard to solve) and a some false positives (people that grind LC as hell, but in reality they dont know much stuff).. Anyway..i wish you good luck!
@dantesmith7859
@dantesmith7859 11 ай бұрын
I wrestled with this one for a couple hours... I was trying to store the prefix sum, not the remainder, and I was having a tough time making that work. Storing the remainders is a great idea, and made the code much more concise! Thanks!
@kuancs1
@kuancs1 3 ай бұрын
Dude if I was in your shoes and realised that I was effectively ramming my head in a wall for a few hours, I would definitely not have the calmness of mind you do. Admire the positivity.
@mirceskiandrej
@mirceskiandrej 2 жыл бұрын
This is not a medium question. It is hard, borderline extreme. If you see the solution, it becomes easy since it's memorable, but you cannot average easy and hard to get a medium question 😃
@shanemarchan658
@shanemarchan658 2 жыл бұрын
ikr. for days ive been trying LOL... really out of the box thinking to come up with this
@shivamshah6579
@shivamshah6579 2 жыл бұрын
100% true!
@CS_n00b
@CS_n00b Жыл бұрын
I was asked this question for a new grad job at a small company fml
@avanishgvyas1992
@avanishgvyas1992 5 ай бұрын
Nice explanation. Impossible to come up with this solution in 25 minutes while under stress in an interview.
@redblacktech
@redblacktech 7 ай бұрын
awesome vid! i'd like to add that the optimized solution is like two-sum in the sense that we're caching complementary values. once you see it this way it becomes intuitive, however, there's no way in hell the average person is going to figure that out without tons of practice doing leetcode questions specifically 🙃 i'd ALSO like to add a one line intuition for the key point of this video: if we see two numbers that when % by k have the same remainder, then those numbers are either k away from each other (or multiple of k away from each other) - and this is exactly what the problem is asking us to find
@finchshi4342
@finchshi4342 2 жыл бұрын
bro you are my favorite leetcode channel
@NeetCode
@NeetCode 2 жыл бұрын
Appreciate that :)
@erikshure360
@erikshure360 2 жыл бұрын
yeah, fuck this problem.
@hanklin4633
@hanklin4633 2 жыл бұрын
Is it possible to think of hashing the remainder in an actual interview? What 'intuition' could anyone even come up with it in the first place?
@adam-zy5tb
@adam-zy5tb 2 жыл бұрын
wouldn't space complexity be O(k) since you are storing at most k entries in the hashmap? i.e. if k = 6 you are storing at most 6 entries since the remainder would never be more than 5 (+1 more for the 0 edge case)
@ivankok8399
@ivankok8399 2 жыл бұрын
Nice solution and explanation. I was struggling to find a faster solution, but this duplicate remainder approach is very creative!
@AlexN2022
@AlexN2022 4 ай бұрын
the easier-to-come-up-with solution can still work: 1. calculate prefix array and store in a map (sum->leftmost index where found) 2. r = 0; r < size; r++ 3. calculate the current rmdr = sum%k 4. if we could find a sub-array on the left with sum=rmdr, we could remove that subarray from [0:r] and sum%k would be 0 5. look for rmdr in the map. If found && index < r - we have found the sub-array to remove
@metarun
@metarun Ай бұрын
dude.. your setup to explain these problems is very efficient. Thanks for putting in the hardwork. cheers
@Dumbastic
@Dumbastic 2 жыл бұрын
Thank you for the clear explanation, I saw the solution before, but I couldn't get behind why it was neccessary to have a duplicated modulo result value in the array. You were able to explain it in a simple manner, appreciate it a lot! Keep up the good work! :)
@CreeperFace75
@CreeperFace75 2 жыл бұрын
great vid! No idea how u come out with these solutions but they make perfect sense
@vadimkokielov2173
@vadimkokielov2173 2 жыл бұрын
first i want to make sure you, but also anyone else knows. I am not writing suggestions because I don't need your videos and the help they give. I need them a lot. I am intensively preparing for an interview. Whatever I write is anything I discover on top of your solutions. That said...You can spare the map and use a hash set. Just keep it trailing behind by one index, so you don't get any invalid values. I am sure you know this solution, and if you decided not to explain it because the mind xxxx of the problem itself is pain enough, then I absolutely agree with you. It's worth pointing out, however.
@hershjoshi3549
@hershjoshi3549 8 ай бұрын
yeah you can def do it with a set and a prev value where prev = sum % k. Personally I find the hashmap solution a little easier to understand and remember.
@priyankachoudhary3694
@priyankachoudhary3694 2 жыл бұрын
Amazing explanation! I don't think I would have been ever able to understand this question without your elegant and detailed explanation about what works and what doesn't work and why it doesn't work.
@varunshrivastava2706
@varunshrivastava2706 2 жыл бұрын
I was asked the same question in my Accolite Digital interview, glad I had already solved it before otherwise I would have been doomed!!!!
@Ryan-g7h
@Ryan-g7h 4 ай бұрын
Hey guys also don't forget this video is missing a key detail: look into why we use elif i - remainder[r] > 1 instead of >=. It ties to the {0:-1} and a edge case such as [6,1,2], k = 6 -> should false but if we do >= return True
@rongrongmiao3018
@rongrongmiao3018 2 жыл бұрын
I hate math questions. To solve this problem all we need to know is that (a-b)%c = ((a%c) - (b%c)) % c. so to get a-b mod c = 0, just need to have this: a mod c = b mod c
@vdyb745
@vdyb745 2 жыл бұрын
Awesome explanation.... for an insane problem. Great work !!!!!
@algosavage7057
@algosavage7057 2 жыл бұрын
just best. I'm watching you for about a year and just wanna say that u'r the best! Thanks for ur job!
@tusharnain6652
@tusharnain6652 2 жыл бұрын
Only explanation that my brain understood. Thank you Neetcode.
@poptart007-b2r
@poptart007-b2r 2 жыл бұрын
Omg the the solution is so damn cool ! I tried out the same lines you talked about in the beginning but it led me nowhere so i was feeling pretty dumdum :p Thank you for your clear explanation as always, it really helps :)
@shadowthehedgehog2727
@shadowthehedgehog2727 2 жыл бұрын
Damn this solution is crazy.. i don’t think I would even think of this
@danielcontreras9343
@danielcontreras9343 2 жыл бұрын
I am a continuous sub array
@sitam-meur4317
@sitam-meur4317 2 жыл бұрын
This solution is just awesome !!! Thanks @NeetCode .
@SomneelMaity
@SomneelMaity 2 жыл бұрын
Amazing Explanation Bro. Your explanation videos made my DSA skills far better.
@shelbys4252
@shelbys4252 2 жыл бұрын
only leetcoder who makes sense tbh. Well done.
@jitpatel1105
@jitpatel1105 4 ай бұрын
Nice Explanation,Thank You
@samridhanand4926
@samridhanand4926 8 ай бұрын
The thought process that helped me get to the solution was by thinking of the problem Largest Subarray with sum 0, as we use hashmap to store the sum with index.
@chandamwenechanya8614
@chandamwenechanya8614 2 жыл бұрын
Hey neet, this is neat!
@henryrussell7392
@henryrussell7392 2 жыл бұрын
Amazing explanation as always
@anirbannandy9104
@anirbannandy9104 2 жыл бұрын
Definitely Like Your Work Bro......Your Explanation Rocks!!!!
@andrewpagan
@andrewpagan 2 жыл бұрын
Thank you so so so so soooo much for this. I was on the right track with modulo and thinking of a sliding window, but was missing the last piece with prefix sum.
@mrunalajitjoshi1512
@mrunalajitjoshi1512 2 жыл бұрын
You got a new subscriber!!
@aadityakiran_s
@aadityakiran_s 8 ай бұрын
Got asked a harder variation of this in a Google interview. No real hint was also provided by the interviewer. I suppose luck is also a factor. If you've seen the problem before or if you're able to fit whatever problem, you get into the pattern that you've seen before.
@meetsoni1938
@meetsoni1938 2 жыл бұрын
You made it very easy for me 🔥🔥💯
@clumsyroad4026
@clumsyroad4026 7 ай бұрын
Your original trains of thought about the 2sum problem as well as a prefix sum approach were also doable, if you had dived deeper into them and made minor modifications. Here is a 2sum-like approach to solving this problem in one pass: class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: seen = set() prv = cur = 0 for x in nums: cur, prv = (cur + x) % k, cur if cur in seen: return True seen.add(prv) return False
@ayushidalal5488
@ayushidalal5488 2 жыл бұрын
Hey, I'm new to this channel. I loved how you explained it so easily! Thanks :)
@bluesteel1
@bluesteel1 8 ай бұрын
I feel you need to be good at math to crack this one on your own.
@beinghappy9223
@beinghappy9223 7 ай бұрын
Amazing intuition
@ShivangiSingh-wc3gk
@ShivangiSingh-wc3gk 5 ай бұрын
Yeah, after coming to prefix sums, I couldnt think about this so tricky either you see the math or you dont
@venkatasundararaman
@venkatasundararaman 2 жыл бұрын
I have been watching your videos and May be it helped I don’t know but I had the same idea to solve the problem before seeing the solution 😃
@rishabhraj8233
@rishabhraj8233 Жыл бұрын
great explanation bro💗
@vinuk.vijayakumar8023
@vinuk.vijayakumar8023 2 жыл бұрын
used this to solve 974. made a few changes. def checksumarray_k(nums, k): remainder={0:[-1]} total=0 count=0 for idx, element in enumerate(nums): total+=element r=total%k if r not in remainder: remainder[r]=[idx] else: count+=len(remainder[r]) remainder[r].append(idx) return count
@mojedsamad7184
@mojedsamad7184 Жыл бұрын
What if we wanted to know where or wich list entries give us this multiple?
@shikharathaur5179
@shikharathaur5179 2 жыл бұрын
Very well explained !
@MrAdnan252
@MrAdnan252 3 ай бұрын
Is the two consecutive 0's not a valid input? You mentioned it, and as you said it wouldnt change the remainder from 23, so how do you detect it as a solution?
@sidazhong2019
@sidazhong2019 Жыл бұрын
2 sum or sliding windows. Your false ideas were exactly what I was trying to do.
@fazilshafi8083
@fazilshafi8083 11 ай бұрын
Java Solution: class Solution { public boolean checkSubarraySum(int[] nums, int k) { HashMap map = new HashMap(); // To store int prefixSum = 0; map.put(0, -1); for (int i = 0; i < nums.length; i++) { prefixSum += nums[i]; int remainder = k == 0 ? prefixSum : prefixSum % k; if (map.containsKey(remainder)) { int length = i - map.get(remainder); if (length >= 2) { return true; } } else { map.put(remainder, i); } } return false; } }
@IK-xk7ex
@IK-xk7ex Жыл бұрын
Yep, it's hard to come up with the part 'i-remainder[r] > 1' by my own. It's great that we leave in the era of streaming to gain best practices
@unknown_manushya
@unknown_manushya Жыл бұрын
I managed to do this on my own with prefix sum approach. My approach is different though and is more than O(n). Following is the code. bool checkSubarraySum(vector& nums, int k) { int sum = 0; unordered_map hash; for (int i = 0; i < nums.size(); i++) { sum += nums[i]; if (!i) { hash[sum] = i; continue; } if (sum % k == 0) return true; int j = 0; while (k * j < sum) { int rem = sum - k * j; if (hash.count(rem) && i - hash[rem] >= 2) { return true; } j++; } if (!hash.count(sum)) hash[sum] = i; } return false; }
@vedbhanushali608
@vedbhanushali608 Жыл бұрын
thanks, great intution.
@lesterdelacruz5088
@lesterdelacruz5088 10 ай бұрын
Mind blown. Who would've come up with that trick from the get go haha?
@mohammadkareem1187
@mohammadkareem1187 2 жыл бұрын
Very elegant explanation. Thanks a lot. Can you please do Leetcode 2060 as well?
@mariotheguy123
@mariotheguy123 11 ай бұрын
thank you neet
@mohamed_ellithy
@mohamed_ellithy 2 жыл бұрын
AMAZING IDEA 😍🌹
@kaushik.aryan04
@kaushik.aryan04 2 жыл бұрын
I think because of this approach this should have been marked as hard problem.
@tomtran6936
@tomtran6936 Жыл бұрын
There is a step after calculating r you can also check if r == 0 return True
@Will-dr9cf
@Will-dr9cf Жыл бұрын
The time complexity of the brute force solution (by summing up the sub-arrays in sliding windows with cumulative sum) seems to be O(n!), which is worse than O(n^2).
@mattjm007
@mattjm007 2 жыл бұрын
Well done on this video
@srinivasareddychalla-i2o
@srinivasareddychalla-i2o 7 ай бұрын
So key point here is if prefixsum%k=r and (prefixsum+x1+x2+•••••+xn)%k=r then undoubtedly x1+x2+•••••+xn is multiple of k
@irarose3536
@irarose3536 2 жыл бұрын
Thanks!
@abhishekgururani6993
@abhishekgururani6993 2 жыл бұрын
Another way to handle the edge case when prefix sum will itself be a multiple of k, arr = [24,0,2] k = 6, [24,0] subarray sum is a multiple of 6. if(prefSum % k == 0 && idx > 0) return true;
@vinayakhaunsnur1327
@vinayakhaunsnur1327 Жыл бұрын
great solution
@DJSTEVE42
@DJSTEVE42 2 жыл бұрын
Does any one know why when we encounter a remainder that already exists in the hash map, there exists a sum that is %k ?
@dragonoid296
@dragonoid296 2 жыл бұрын
because if the remainder wraps around, we know that it changed by k
@Everafterbreak_
@Everafterbreak_ Ай бұрын
If you get this in an interview and you haven't seen this before you're definitely cooked, theres no way any person will come out with this intuition.
@rajeevkri123
@rajeevkri123 2 жыл бұрын
Java solution for the same public boolean checkSubarraySum(int[] nums, int k) { HashMap map = new HashMap (); int sum = 0; map.put(0, -1); boolean found = false; int n = nums.length; for(int i=0; i< n; i++) { sum = sum + nums[i]; int hash = sum % k; if(map.containsKey(hash)) { int diff = i - map.get(hash); if(diff>=2) { found = true; break; } } else { map.put(hash, i); } } return found; }
@bokistotel
@bokistotel 17 күн бұрын
I think this is not about having a math brain, it is about have you seen enough of these similar patterns from the past so your brain gets used to it.
@ujjaldas9179
@ujjaldas9179 7 ай бұрын
thanks
@ratnadeeppaul
@ratnadeeppaul 3 ай бұрын
what happens if r is already in the hashmap but index difference is less than 1?
@edwardteach2
@edwardteach2 3 ай бұрын
U a Continuous Subarray Sum God
@yashpathak9285
@yashpathak9285 2 жыл бұрын
You are so smart!! I would like to elect you president.
@madhuj6912
@madhuj6912 5 ай бұрын
Can someone tell me whats this , what is x and n are that values of array " An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k "
@codeguru4
@codeguru4 8 ай бұрын
hi @neetcode i Try to solve it Using Sliding Window It passes Most of the Test Csaes but if array consist of 0 then its failing 93/99 test cases are passed but this one if failing nums = [1,3,6,0,9,6,9]. , k = 7 output : True if len(nums) < 2: return False currSum = 0 totalSum =nums[0] l= 0 for r in range(1, len(nums)): currSum = nums[l]+ nums[r] totalSum +=nums[r] if currSum % k == 0 or totalSum % k == 0 : return True l+=1 if totalSum % k == 0: return True return False could you please See It Please
@bhushanmahajan2150
@bhushanmahajan2150 2 жыл бұрын
Could you please make videos on systems designs as well, if possible?
@ariaXP1
@ariaXP1 2 жыл бұрын
Can you do 410. Split Array Largest Sum? Thank you!!
@SaahasBuricha
@SaahasBuricha 5 ай бұрын
this is insane
@avanishraj386
@avanishraj386 Жыл бұрын
Could it be solved using Brute force method? If solved, then how?
@zz-yy-xx
@zz-yy-xx 7 ай бұрын
OMG, so tricky!!!!!
@kaioken1999
@kaioken1999 2 жыл бұрын
Dope
@santoshr4212
@santoshr4212 2 жыл бұрын
this should have been a hard problem.
@experiment0003
@experiment0003 Жыл бұрын
Python is so easy for OA. Sadly, I'm more comfortable writing in Java. Imagine "remainder = { 0, -1 }". Java would be first import Map and hashMap, then Map remainder = new HashMap(); map.put(0, -1);. So sad. So so sad!
@masternobody1896
@masternobody1896 2 жыл бұрын
me as a day of life an unemployed dude :(
@MDEMANURRAHAMAN-
@MDEMANURRAHAMAN- 2 жыл бұрын
[5,0,0,0] 3 Expected output : True How can it possible ??
@jsalaat
@jsalaat 2 жыл бұрын
0 and 0 are a continuous subarray hence making 0+0 = 0%k expects to fulfil the condition. hence returns true
@vbcarnage
@vbcarnage 2 жыл бұрын
i did not try it but it looks like this could be solved with segment trees
@heetshah7292
@heetshah7292 2 жыл бұрын
I was recently asked this question in an interview and I was solving it through a two-pointer approach but I failed to optimize and got rejected 😥
@sureshsingam7291
@sureshsingam7291 2 жыл бұрын
which company??
@maheshj01
@maheshj01 7 ай бұрын
This problem is mainly optimization.
@Dannnneh
@Dannnneh 7 ай бұрын
Is there a real life use case for an algorithm for this?
@sabukuna
@sabukuna 7 ай бұрын
doubt it
@RiazKhan-b6e
@RiazKhan-b6e 2 ай бұрын
How can a person reached this solution without exploring discussion or solution section?
@rahulbhardwaj4380
@rahulbhardwaj4380 2 жыл бұрын
Great concept but really this approach is difficult to come up with.
@gabrielignat4371
@gabrielignat4371 23 күн бұрын
that should be a HARD question
@imjusttryingtobesafelol5909
@imjusttryingtobesafelol5909 Жыл бұрын
i laughed when i saw the solution its sooooooo clever
@charanpasupula3763
@charanpasupula3763 2 жыл бұрын
Ninja level
@youssefel-shabasy833
@youssefel-shabasy833 7 ай бұрын
oh god
@mayanksood4709
@mayanksood4709 2 ай бұрын
Bro this is impossible for me to come up with!
@yatri6329
@yatri6329 2 жыл бұрын
Great yaar i was missing some cases ... thanks
@PREETIGUPTA-l8j
@PREETIGUPTA-l8j 7 ай бұрын
Still unable to understand how it has checked all subarrays' sum
@eddiej204
@eddiej204 2 жыл бұрын
How much IQ is required here to come up with the solution on the first look?
@Ginger_Hrn
@Ginger_Hrn 4 ай бұрын
idk, last time I solved a matrix problem to which the algorithm was made by a russian computer scientist to solve THAT particular type of problem.
Subarray Sum Equals K - Prefix Sums - Leetcode 560 - Python
15:19
4Sum - Leetcode 18 - Python
15:28
NeetCode
Рет қаралды 87 М.
VIP ACCESS
00:47
Natan por Aí
Рет қаралды 30 МЛН
1% vs 100% #beatbox #tiktok
01:10
BeatboxJCOP
Рет қаралды 67 МЛН
Beat Ronaldo, Win $1,000,000
22:45
MrBeast
Рет қаралды 158 МЛН
523. Continuous Subarray Sum | Prefix Sums | Hash Map
11:52
Aryan Mittal
Рет қаралды 7 М.
AI Is Making You An Illiterate Programmer
27:22
ThePrimeTime
Рет қаралды 261 М.
Subarray Sums Divisible by K - Leetcode 974 - Python
16:41
NeetCodeIO
Рет қаралды 20 М.
What P vs NP is actually about
17:58
Polylog
Рет қаралды 148 М.
Minimum Size Subarray Sum - Leetcode 209 - Python
12:30
NeetCode
Рет қаралды 102 М.
Deepseek Changes Everything
10:26
NeetCodeIO
Рет қаралды 84 М.
Fast Inverse Square Root - A Quake III Algorithm
20:08
Nemean
Рет қаралды 5 МЛН
10 Signs Your Software Project Is Heading For FAILURE
17:59
Continuous Delivery
Рет қаралды 38 М.
для всей семьи
0:56
Стакановец
Рет қаралды 191 М.
Самые простые строительные леса
0:54
Канал ИДЕЙ
Рет қаралды 1 МЛН
ЛИТВИН / ПРАНК С ГРИМОМ / Shorts #upx #shorts
0:59
Do YOU Understand WHAT JUST HAPPENED!? 😂 #shorts
0:57
LankyBox World
Рет қаралды 1,6 МЛН