Count Subarray sum Equals K | Brute - Better -Optimal

  Рет қаралды 337,519

take U forward

take U forward

Күн бұрын

Пікірлер: 274
@AyushVerma-wu3nn
@AyushVerma-wu3nn Жыл бұрын
Just when I think the video is getting long enough for a simple problem, I go search the web and find not a single tutor with such a powerful explanation!
@itzmartin20
@itzmartin20 Жыл бұрын
When I first started DSA, I was just so scared of the code and knowing very little about the logic and the intuition behind but Striver you are the one who has ever showed the completely difference - Extreme natural approach and observation and crystal clear logic. You've made the coding fun and interesting toward people like me. Hats off for your dedication! Understood!
@utkarshverma3314
@utkarshverma3314 Жыл бұрын
i am doing his dsa sheet , the array part and almost every question has a completely different logic and approach and its becoming quite frustrating as im not able to come up with the solutions so do i just keep solving more problems or am i doing something wrong
@anshlyk
@anshlyk Жыл бұрын
keep going! I was in the same boat, you'll slowly be able to form logic@@utkarshverma3314
@akworld2739
@akworld2739 Жыл бұрын
@@utkarshverma3314 same problem i am also facing
@VivekKumar-kx2zf
@VivekKumar-kx2zf 7 ай бұрын
ashishbhattacharyya yup, it works for me.
@Sankalp-sd6fm
@Sankalp-sd6fm 7 ай бұрын
could you please tell if i should make notes ?? how do i make them so that i dont put hours in it
@daayush6654
@daayush6654 Жыл бұрын
I saw this video at around 10 am in college, was only able to think of o(n²) solution, I took the pause at your hint of using prefix sum array, kept thinking for some time while in college lectures but was able to get the solution at around 6pm 😝, I know it took time but it felt good to actually think of the solution, please keep up the consistency
@andrewcenteno3462
@andrewcenteno3462 Жыл бұрын
This man is my hero, I struggled so much with this question to visualize it and subsequent problems like it. I've done ove 270 LC questions, but this man made it so simple
@abhijeetmishra3804
@abhijeetmishra3804 Жыл бұрын
understood bhaiya . You can not even imagine how much people love u and praise you and speak about your videos all the time. I am sure u get hiccups every now and then . Live long bhaiya u are our real teacher.
@NikhilKoushik4b4
@NikhilKoushik4b4 Жыл бұрын
I saw many times but I couldn't understand...But now i finally understood and realised that ur explaination is too good...!
@gamerversez5372
@gamerversez5372 Жыл бұрын
Instead of adding 0 in the hashmap, we can just use the statement if(sum==k) ans++; That works fine. See the Below Code int subarraySum(vector& nums, int k) { int ans=0; unordered_map x; int sum=0; for(int i=0;i
@00RohitRoshan
@00RohitRoshan Жыл бұрын
very good .
@00RohitRoshan
@00RohitRoshan Жыл бұрын
` if(x.find(sum-k)!=x.end()) ans+=x[sum-k]; ` And why this check before incrementing and. class Solution { public: int subarraySum(vector& nums, int k) { int ans=0,sum=0; unordered_map x; for(int i=0;i
@kushalswarup2662
@kushalswarup2662 Жыл бұрын
brilliant
@the_avii_7
@the_avii_7 2 ай бұрын
It will fail for the test case: [1,-1,0] k = 0.
@puneetnj
@puneetnj Жыл бұрын
So here, if in the question it is stated that it contains only positive as in codestudio then we can apply 2-pointer(Sliding window) as done in longest subarray with sum k. TC: O(N) SC: O(1) Else, if it contains both positive and negative HashMap is optimal
@AnuroopLSabu-mp8wm
@AnuroopLSabu-mp8wm Жыл бұрын
Its really amazing that you are taking your time in explaining via the dry run. It helps me a lot. Thanks :)
@srija0608
@srija0608 Ай бұрын
@takeUforward when you explained the logic behind taking the 0 prefix-sum and the count value, my mind was actually blown! This was an amazing explanation, thank you❤
@davidmwangi4312
@davidmwangi4312 6 ай бұрын
Struggled to understand this solution, now understood, Keep up the great work Striver
@aryansinha1818
@aryansinha1818 Жыл бұрын
You have given more than anyone can ask for. Thank you for all your support and such amazing videos. They are really helpful. Just a small thing can we have a dark mode setting for "take you forward" pages.
@takeUforward
@takeUforward Жыл бұрын
You can build one chrome extension may be ;)
@dom47
@dom47 Жыл бұрын
appreciates striver by telling "u have given more than anyone can ask" and proceeds to place demand .
@yashjoon3889
@yashjoon3889 Жыл бұрын
@@takeUforward lol would be a good project for the resume?
@manvinmusic9239
@manvinmusic9239 Жыл бұрын
striver actually give the dark mode option
@Manishgupta200
@Manishgupta200 Жыл бұрын
That's really amazing 🤩Striver! code is too sort but logic is superb for the optimal. from brute (TC-> O(N^2), SC -> O(1)) to optimal (TC -> O(N) when using unordered_map, O(N * log N) when using ordered map, SC -> O(N) for using map data structure.
@Someone-k4d
@Someone-k4d 3 ай бұрын
What an excellent explanation! Even after watching another video 6-7 times, l could not understand it. But understood this perfectly after watching only once!
@alishashaikh3859
@alishashaikh3859 Жыл бұрын
Thank you so much. I saw many other youtuber's video but this video is the best . I was able to understand after watching this video for 2 times
@mehulthuletiya5638
@mehulthuletiya5638 Жыл бұрын
Timestamps 01:03 - Problem Statement 01:13 - Sub-array definition 01:52 - Example 03:13 - Brute force solution 06:07 - Complexity 06:29 - Better solution 08:07 - Complexity 08:21 - Optimal Solution 08:41 - Prefix sum concept 09:35 - Example 13:55 - Dry run 21:22 - Code 22:38 - Complexity
@mriduljain1981
@mriduljain1981 Жыл бұрын
we can also use sliding window 2 pointer approach for this one code-> int findAllSubarraysWithGivenSum(vector < int > & arr, int k) { int n =arr.size(),sum = 0,cnt = 0,left = 0; for(int right = 0;right k) sum-=arr[left++]; if(sum == k) cnt++; } return cnt; }
@amitranjan6998
@amitranjan6998 Жыл бұрын
It will fail .arr[]=[1] k=0
@mriduljain1981
@mriduljain1981 Жыл бұрын
@@amitranjan6998 yes we just need to add a condition of left
@sujeet4410
@sujeet4410 7 ай бұрын
This explanation is so 100x better than Neetcode's. Thank you !!!
@Dibyadipan
@Dibyadipan 2 ай бұрын
Finally understood the prefix sum concept after u explained by doing a dry run! Thanks Striver!❤✌🏼
@biswadevsarkar2830
@biswadevsarkar2830 5 ай бұрын
mpp[0] = 1 helps us to take the count when (sum == k ). Because when sum will be k, then remove will be 0. And then mpp[1] will give us 0, which will be added to the count. If we don't store 0 to our map. then we need to handle the case in an extra if condtion. which is if(sum == k) count++;
@piyushchaudhary3195
@piyushchaudhary3195 3 ай бұрын
More optimal solution than striver's: Using two pointers create your imaginary window. If the `sum == k` then increment `count` and move first pointer forward because you no longer need that element to count towards the sum. If `sum > k` then decrease the sum by moving the first pointer forward. If `sum < k` then increase the sum by using the second pointer. If the second pointer has gone out of range start decreasing the window size by incrementing the first pointer. int findAllSubarraysWithGivenSum(vector& arr, int k) { int count = 0; int i = 0; int j = 1; int sum = arr[i]; while(i
@mythologyKnowledge6581
@mythologyKnowledge6581 3 ай бұрын
It will work only for non negative numbers in array.As u are moving forward assuming that sum will not decrease,think about it
@piyushchaudhary3195
@piyushchaudhary3195 3 ай бұрын
@@mythologyKnowledge6581 Yeah, you 're right. It's only optimal for positives.
@bpratikvinod8110
@bpratikvinod8110 7 ай бұрын
The sliding window approach actually performs better with O(n) time complexity. int subarraySum(vector& nums, int sum) { int count = 0; int currSum = 0; unordered_map sumFreq; for (int i = 0; i < nums.size(); ++i) { currSum += nums[i]; if (currSum == sum) count++; if (sumFreq.find(currSum - sum) != sumFreq.end()) count += sumFreq[currSum - sum]; sumFreq[currSum]++; // If currSum becomes greater than sum, // subtract elements from the start while (currSum > sum) { currSum -= nums[i - count + 1]; sumFreq[currSum]--; if (sumFreq[currSum] == 0) sumFreq.erase(currSum); count--; } } return count; }
@ritu-ql8fk
@ritu-ql8fk 17 күн бұрын
But the thing is sliding window approach won't work for negative numbers
@bpratikvinod8110
@bpratikvinod8110 17 күн бұрын
@@ritu-ql8fk Just remove the extra while loop
@Anurag-fk3op
@Anurag-fk3op 7 ай бұрын
16:29 if we write if(sum==k) count++ We don't need to include 0 at beginning
@SAI-q1v
@SAI-q1v 6 ай бұрын
good one!!
@abhijitkumarsinha
@abhijitkumarsinha 6 ай бұрын
THAT IS WHAT I WAS DOING
@indroneelgoswami5654
@indroneelgoswami5654 3 ай бұрын
thank you
@infernogamer52
@infernogamer52 Жыл бұрын
Understood Bhaiya! This was a tough one to understand for me...will soon revisit it Thank you🙏
@MukeshH.P
@MukeshH.P Жыл бұрын
Amazingly Understood, Thank you for such a in depth thought process
@pulkitgupta669
@pulkitgupta669 Жыл бұрын
Understood Striver ❤. You are a living legend sir. 🤩🤩
@rushabhajain3977
@rushabhajain3977 Жыл бұрын
Excellent explanation yaar! Great to see such kind of explanations that guide from brute force to optimised solution in such a detail! Thank you so much and keep making such great videos :)
@cinime
@cinime Жыл бұрын
Understood! Super fantastic explanation as always, thank you very very much for your effort!!
@neerajkumar-ts6om
@neerajkumar-ts6om 3 ай бұрын
I think I should watch it again, have watched a lot of your video this is the first which I didn't understand in the first go.
@nopecharon
@nopecharon Жыл бұрын
you are topG of DSA
@AmanThakur-ve6ji
@AmanThakur-ve6ji Жыл бұрын
God for beginner❤hats of u bhaiya
@fluxdevyt
@fluxdevyt Жыл бұрын
Bhaiya ye Question ka video dekhne se phale hoo gaya 😁😁Only Minor change int findAllSubarraysWithGivenSum(vector < int > & nums, int k) { int right = 0; int left = 0; int count = 0; long long sum = nums[0]; int n = nums.size(); while(right < n){ while(left k){ sum = sum - nums[left]; left++; } if(sum == k){ count++; } right++; if(right < n){ sum+=nums[right]; } } return count; }
@nikiteshnandale8264
@nikiteshnandale8264 Жыл бұрын
It seems like you have edited your voice in the video and made it soft, I am missing that bold voice which is there in the DP playlist. Please don't edit your voice, you don't have to adjust yourself for us. We like the way you are, the original STRIVER🔥🔥
@takeUforward
@takeUforward Жыл бұрын
But we need to look at the future, we want to go global, so audio quality has to be maintained, I hope you get that :)
@abdulrehmaan153
@abdulrehmaan153 Жыл бұрын
​@@takeUforwardand we love you for that too, It's sort of unconditional 😂
@spartaninfo3273
@spartaninfo3273 3 ай бұрын
Banee...
@pradeepsahu5500
@pradeepsahu5500 20 күн бұрын
My optimized Code different from the given optimized code, with same time complexity : int subArraySumOptimized(vector &nums, int k) { int n = nums.size(); int summation = 0; map mpp; int count = 0; for (int i = 0; i < n; i++) { summation += nums[i]; if (summation == k) { count++; } if (mpp.find(summation - k) != mpp.end()) { count += mpp[summation - k]; } mpp[summation]++; } return count; }
@code710
@code710 Жыл бұрын
Hi bhaiya it would be really helpful if you can give similar question links for practise after every question explanation!!
@DTALKS01
@DTALKS01 5 ай бұрын
for me optimal is little hard but after see 2-3 time video , got easly understand
@graviton001
@graviton001 4 ай бұрын
Was able to think O(N^2) approach and totally underatood optimal solution too 😊
@vishnupandey3390
@vishnupandey3390 Жыл бұрын
thanks striver you have really explained this so well god bless you you are a wonderful teacher for many 🙏🙏
@deepanshuverma6237
@deepanshuverma6237 5 ай бұрын
Regarding putting (0,1) int the Hashmap initally : Let consider somehow the preSum got exactly equal to our k, means now the sub-array till that presum element gives us the k (~ preSum-k = 0). means whenever we find our preSum touching the k value, we need to increment count but we will not be able to find it in hashMap as it is yet to be inserted that why either increment count based on if preSum-k = 0 or put a (0,1) in hashmap to automatically finding preSum-k = 0 in the hashMap. int preSum = 0, count = 0, start = 0; Map mp = new HashMap(); for(int i=0;i
@KrishnaChauhan-fo4ky
@KrishnaChauhan-fo4ky 27 күн бұрын
class Solution { public: int subarraySum(vector& nums, int k) { int psum=0,e=0,count=0; unordered_maphashmap; hashmap[0]=1; while(e
@dayashankarlakhotia4943
@dayashankarlakhotia4943 Жыл бұрын
Previous explanation and current explanation is good .understood
@vidhanshuborade5977
@vidhanshuborade5977 Жыл бұрын
Excellent explanation, understood ! ✨
@RaviKumar-sn6tu
@RaviKumar-sn6tu 8 ай бұрын
understood captain...thanks
@schan263
@schan263 Жыл бұрын
Thanks for the great video. I don't see how I can come up with the optimal solution during the interview without hint from the interviewer.
@ashj1165
@ashj1165 10 ай бұрын
though I am still figuring out on the map[0]=1 part but surely the rest of the part was indeed clear. thanks for these videos.
@JUST_C0DE
@JUST_C0DE 10 ай бұрын
if you select no element in sub array then , map[0]=1
@niketandoddamani1093
@niketandoddamani1093 29 күн бұрын
That Dry run! 🔥
@GarimaShukla-jq8sf
@GarimaShukla-jq8sf 4 ай бұрын
Striver you are great 🙌🙌 .I just want to thank you ❤️.
@ProductivityPowerhouse0109
@ProductivityPowerhouse0109 Жыл бұрын
Striver you can make these playlists a bit fun if you allow your viewers to suggest you problems they think discussable !! btw loving the playlist
@abdulrehmaan153
@abdulrehmaan153 Жыл бұрын
Plz don't ruin it for us 😂😂😂
@dogwoofwoof8154
@dogwoofwoof8154 Жыл бұрын
plz no
@impalash_ag
@impalash_ag 5 ай бұрын
Storing (0,1) in the hashmap is bit confusing, instead we can just increase a check i.e. if(currSum == k) count++. The more readable code(JAVA) will look like this: public int subarraySum(int[] nums, int k) { int currSum = 0, count = 0; int n = nums.length; HashMap map = new HashMap(); for(int i=0; i
@varunpalsingh3822
@varunpalsingh3822 Жыл бұрын
Really good explanation & kudos to efforts, understood 👍
@VineetKumar-fk2rl
@VineetKumar-fk2rl Жыл бұрын
We can also solve this problem in O(1) space complexity but the T.C will be 2N using two pointer approach.
@kunwar-nw5dd
@kunwar-nw5dd Жыл бұрын
solution blew my mind
@JohadP-v6e
@JohadP-v6e 4 ай бұрын
i still don't get the significance of (0,1) in the map, my answer still got submitted in Leetcode.
@krishnavamsiyerrapatruni5385
@krishnavamsiyerrapatruni5385 Жыл бұрын
Understood. Thank you so much!
@saddubhaiii
@saddubhaiii 5 ай бұрын
Thank you Striver. I owe you❤
@saileshsirari2014
@saileshsirari2014 6 ай бұрын
Without adding to map, you need to count occurrences still not in map public int subarraySum(int[] nums, int k) { int sum=0; int count =0; Map map = new HashMap(); for(int i=0;i
@rohan8758
@rohan8758 7 ай бұрын
Awesome explanation, one approach of sliding window will not work in this problem if array contains negative elements also.
@ayanangshudasmajumder112
@ayanangshudasmajumder112 Жыл бұрын
if instead of specifying map[0]=1 in the beginning if we give a condition that if(preSum == k) { count ++;} Will it be correct Striver bhaiya??
@prigo333
@prigo333 8 ай бұрын
you are awesome bhaiya...
@meghnakhaitan2495
@meghnakhaitan2495 Жыл бұрын
Can you pls pls plsssss do strings before binary search next plsss🙏 ? From 2023 batch🥺. Wish we could have the entire series in our 1st 2nd 3rd yrs
@thebusinesspostt
@thebusinesspostt Жыл бұрын
are we supposed to think of optimal solution on our own. asking because it seems pretty daunting.
@takeUforward
@takeUforward Жыл бұрын
Its not daunting, it is basically a technique, on the basis of this you can solve many questions
@RajeevCanDev
@RajeevCanDev Жыл бұрын
Literally, maybe just because I'm watching while I'm not in complete attention but still the optimal approach feels like it comes with a completely different path as compared to normal intuitive thought process
@sukhpreetsingh5200
@sukhpreetsingh5200 Жыл бұрын
Understood💖amazing explanation
@gamengoaituyen4432
@gamengoaituyen4432 Жыл бұрын
tks for explanation, you are savior
@sahilnayak9000
@sahilnayak9000 10 ай бұрын
❓ You mentioned performing a dry run on the array [3, -3, 1, 1, 1] to understand the significance of initially putting (0, 1) in the map. However, it hasn't been specified which sum we should consider for this particular dry run.
@sahilnayak9000
@sahilnayak9000 10 ай бұрын
Although i understood, if we didn't want to put initially that or if we find it challenging to understand its significance. there is an alternative approach to handle the situation. Another way is when currentSum - given_sum == 0 we just need to increment counter. that's it we can omit to put initially (0,1) pair in map.
@OnstreamGaming
@OnstreamGaming 5 ай бұрын
Thanks for the help raj bhaiya
@parasarora5869
@parasarora5869 3 күн бұрын
Great one ! ❤
@universalcosmologist3675
@universalcosmologist3675 4 ай бұрын
i can think of brute and better solution but optimal can't be thought all by myself but is too confusing
@rajatpatra2593
@rajatpatra2593 Жыл бұрын
Understood ❤️
@AniketKumar-hf2bo
@AniketKumar-hf2bo 10 ай бұрын
understood ,thnx for amazing video ❤❤❤❤❤❤
@NitinKumar-wm2dg
@NitinKumar-wm2dg Жыл бұрын
Thanks bhaiya, understood
@lakshmiprasanna7058
@lakshmiprasanna7058 Жыл бұрын
Understood 💯💯💯
@reshusingh3558
@reshusingh3558 Жыл бұрын
understood sir ,great explanation
@mriduljain6809
@mriduljain6809 Жыл бұрын
Can also do like this: int subarraySum(vector& nums, int k) { unordered_map m; int c = 0; int s=0; for(int i=0;i
@sarangkumarsingh7901
@sarangkumarsingh7901 8 ай бұрын
Awesome Awesome Sir...............
@culeforever5408
@culeforever5408 Жыл бұрын
undestood ✌
@AnkitKumar-sz3by
@AnkitKumar-sz3by Жыл бұрын
thanks really good explination
@NazeerBashaShaik
@NazeerBashaShaik 8 ай бұрын
Understood, thank you.
@utkarshpundeer07
@utkarshpundeer07 15 күн бұрын
Understood 👍
@swapnilingale4164
@swapnilingale4164 Жыл бұрын
Nice explation ❤
@piyushnandardhane1432
@piyushnandardhane1432 Жыл бұрын
Please also make video for count pairs with given sum and divisible by k
@SYCOA12CHAITANYAASOLE
@SYCOA12CHAITANYAASOLE 6 ай бұрын
Understood !! 😍😍
@harshilpatel3205
@harshilpatel3205 3 ай бұрын
Understood 🙏🏻
@YourCodeVerse
@YourCodeVerse Жыл бұрын
Understood✅🔥🔥
@gautamsaxena4647
@gautamsaxena4647 2 ай бұрын
understood bhaiya
@Braveuser-x7j
@Braveuser-x7j Жыл бұрын
nice ..........explanation
@AdityaKumar-ow1rh
@AdityaKumar-ow1rh Жыл бұрын
we can also do this problem by sliding window technique
@sauravchandra10
@sauravchandra10 Жыл бұрын
Understood, thanks!
@kingbadshah452
@kingbadshah452 10 ай бұрын
understood striver thanks
@parshchoradia9909
@parshchoradia9909 Жыл бұрын
Understood Sir!
@himadriroy7980
@himadriroy7980 Жыл бұрын
I just wonder how he writes a piece of code so easily. I just wonder when will I be able to write code in such a way.
@konankikeerthi
@konankikeerthi 5 ай бұрын
Thanks bro. Understood
@madeupofstarstuff3067
@madeupofstarstuff3067 Жыл бұрын
Dronacharya from 21st century!!
@her_soulmate
@her_soulmate Жыл бұрын
Understood 🎉
@AbhishekBhattacharjee-j2m
@AbhishekBhattacharjee-j2m Жыл бұрын
UNDERSTOOD
@oyeesharme
@oyeesharme 2 ай бұрын
thanks bhaiya
@mozsty
@mozsty 6 ай бұрын
very nice. .thankyou
@aashapun6533
@aashapun6533 Жыл бұрын
The Best♥
@YPZanzarukiya
@YPZanzarukiya 4 ай бұрын
Understand
@MohitKumar-o3l1u
@MohitKumar-o3l1u 9 ай бұрын
Understood.
@tarunsatyarthi4355
@tarunsatyarthi4355 Жыл бұрын
Easy to understand code #include int findAllSubarraysWithGivenSum(vector < int > & arr, int k) { // Write Your Code Here map mpp; int sum=0; mpp[0]=1; int count=0; for(int i=0;i
@abdulrehmaan153
@abdulrehmaan153 Жыл бұрын
U complicated it 😂
Pascal Triangle | Finding nCr in minimal time
26:45
take U forward
Рет қаралды 283 М.
SIZE DOESN’T MATTER @benjaminjiujitsu
00:46
Natan por Aí
Рет қаралды 3,1 МЛН
Как Я Брата ОБМАНУЛ (смешное видео, прикол, юмор, поржать)
00:59
If people acted like cats 🙀😹 LeoNata family #shorts
00:22
LeoNata Family
Рет қаралды 23 МЛН
Subarray Sum Equals K - Prefix Sums - Leetcode 560 - Python
15:19
Number of Subarrays with xor K | Brute - Better - Optimal
24:55
take U forward
Рет қаралды 146 М.
Prefix Sum in 4 minutes | LeetCode Pattern
4:13
AlgoMasterIO
Рет қаралды 4,3 М.
The little things MATTER - Sony INZONE M10S
11:36
ShortCircuit
Рет қаралды 19 М.
15 Sorting Algorithms in 6 Minutes
5:50
Timo Bingmann
Рет қаралды 25 МЛН
Kadane's Algorithm | Maximum Subarray Sum | Finding and Printing
20:09
take U forward
Рет қаралды 491 М.
Subarray Sums Divisible by K - Leetcode 974 - Python
16:41
NeetCodeIO
Рет қаралды 18 М.
Count Inversions in an Array | Brute and Optimal
24:17
take U forward
Рет қаралды 242 М.