Count Subarray sum Equals K | Brute - Better -Optimal

Sdílet
Vložit
  • čas přidán 26. 07. 2024
  • Problem Link: bit.ly/3Kn10eZ
    Please watch this video before watching this one: • Longest Subarray with ...
    Notes/C++/Java/Python codes: takeuforward.org/arrays/count...
    We have solved the problem, and we have gone from brute force and ended with the most optimal solution. Every approach's code has been written in the video itself. Also, we have covered the algorithm with intuition.
    Full Course: bit.ly/tufA2ZYt
    You can follow me across social media, all my handles are below:
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    00:00 Intro
    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 Thought process
    13:55 Dry run
    21:22 Code
    22:38 Complexity

Komentáře • 230

  • @itzmartin20
    @itzmartin20 Před 10 měsíci +120

    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 Před 10 měsíci +4

      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 Před 10 měsíci

      keep going! I was in the same boat, you'll slowly be able to form logic@@utkarshverma3314

    • @akworld2739
      @akworld2739 Před 9 měsíci

      @@utkarshverma3314 same problem i am also facing

    • @VivekKumar-kx2zf
      @VivekKumar-kx2zf Před 3 měsíci

      ashishbhattacharyya yup, it works for me.

    • @Sankalp-sd6fm
      @Sankalp-sd6fm Před 3 měsíci

      could you please tell if i should make notes ?? how do i make them so that i dont put hours in it

  • @daayush6654
    @daayush6654 Před rokem +33

    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

  • @AyushVerma-wu3nn
    @AyushVerma-wu3nn Před 10 měsíci +7

    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!

  • @andrewcenteno3462
    @andrewcenteno3462 Před rokem +27

    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 Před 9 měsíci +5

    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.

  • @AnuroopLSabu-mp8wm
    @AnuroopLSabu-mp8wm Před 11 měsíci +5

    Its really amazing that you are taking your time in explaining via the dry run. It helps me a lot. Thanks :)

  • @sujeet4410
    @sujeet4410 Před 3 měsíci +3

    This explanation is so 100x better than Neetcode's. Thank you !!!

  • @alishashaikh3859
    @alishashaikh3859 Před 11 měsíci +1

    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

  • @cinime
    @cinime Před rokem +1

    Understood! Super fantastic explanation as always, thank you very very much for your effort!!

  • @user-fn2jg7ng7q
    @user-fn2jg7ng7q Před 11 měsíci +1

    I saw many times but I couldn't understand...But now i finally understood and realised that ur explaination is too good...!

  • @user-yb1es6mu8g
    @user-yb1es6mu8g Před 11 měsíci +1

    Amazingly Understood, Thank you for such a in depth thought process

  • @davidmwangi4312
    @davidmwangi4312 Před 2 měsíci

    Struggled to understand this solution, now understood, Keep up the great work Striver

  • @Anurag-fk3op
    @Anurag-fk3op Před 3 měsíci +10

    16:29 if we write if(sum==k) count++
    We don't need to include 0 at beginning

  • @gamerversez5372
    @gamerversez5372 Před rokem +8

    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 Před 11 měsíci +2

      very good .

    • @00RohitRoshan
      @00RohitRoshan Před 11 měsíci +1

      ` 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 Před 10 měsíci

      brilliant

  • @puneetnj
    @puneetnj Před 11 měsíci +15

    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

  • @vidhanshuborade5977
    @vidhanshuborade5977 Před rokem +2

    Excellent explanation, understood ! ✨

  • @Manishgupta200
    @Manishgupta200 Před rokem +6

    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.

  • @vishnupandey3390
    @vishnupandey3390 Před 11 měsíci

    thanks striver you have really explained this so well
    god bless you
    you are a wonderful teacher for many 🙏🙏

  • @krishnavamsiyerrapatruni5385

    Understood. Thank you so much!

  • @infernogamer52
    @infernogamer52 Před rokem +2

    Understood Bhaiya! This was a tough one to understand for me...will soon revisit it
    Thank you🙏

  • @rushabhajain3977
    @rushabhajain3977 Před 8 měsíci +1

    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 :)

  • @varunpalsingh3822
    @varunpalsingh3822 Před rokem +1

    Really good explanation & kudos to efforts, understood 👍

  • @aryansinha1818
    @aryansinha1818 Před rokem +22

    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  Před rokem +24

      You can build one chrome extension may be ;)

    • @dom47
      @dom47 Před rokem +21

      appreciates striver by telling "u have given more than anyone can ask" and proceeds to place demand .

    • @yashjoon3889
      @yashjoon3889 Před rokem +4

      @@takeUforward lol would be a good project for the resume?

    • @manvinmusic9239
      @manvinmusic9239 Před rokem +4

      striver actually give the dark mode option

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 Před rokem +1

    Previous explanation and current explanation is good .understood

  • @AmanThakur-ve6ji
    @AmanThakur-ve6ji Před rokem +1

    God for beginner❤hats of u bhaiya

  • @pulkitgupta669
    @pulkitgupta669 Před 11 měsíci +1

    Understood Striver ❤. You are a living legend sir. 🤩🤩

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 Před rokem

    Understood💖amazing explanation

  • @GarimaShukla-jq8sf
    @GarimaShukla-jq8sf Před 4 dny

    Striver you are great 🙌🙌 .I just want to thank you ❤️.

  • @sauravchandra10
    @sauravchandra10 Před rokem

    Understood, thanks!

  • @reshusingh3558
    @reshusingh3558 Před rokem

    understood sir ,great explanation

  • @gamengoaituyen4432
    @gamengoaituyen4432 Před rokem

    tks for explanation, you are savior

  • @NazeerBashaShaik
    @NazeerBashaShaik Před 3 měsíci

    Understood, thank you.

  • @bpratikvinod8110
    @bpratikvinod8110 Před 2 měsíci +1

    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;
    }

  • @RaviKumar-sn6tu
    @RaviKumar-sn6tu Před 3 měsíci +1

    understood captain...thanks

  • @AniketKumar-hf2bo
    @AniketKumar-hf2bo Před 6 měsíci

    understood ,thnx for amazing video ❤❤❤❤❤❤

  • @NitinKumar-wm2dg
    @NitinKumar-wm2dg Před rokem

    Thanks bhaiya, understood

  • @AnkitKumar-sz3by
    @AnkitKumar-sz3by Před 10 měsíci

    thanks really good explination

  • @prigo333
    @prigo333 Před 4 měsíci +1

    you are awesome bhaiya...

  • @graviton001
    @graviton001 Před 4 dny

    Was able to think O(N^2) approach and totally underatood optimal solution too 😊

  • @OnstreamGaming
    @OnstreamGaming Před měsícem

    Thanks for the help raj bhaiya

  • @kunwar-nw5dd
    @kunwar-nw5dd Před rokem

    solution blew my mind

  • @saddubhaiii
    @saddubhaiii Před měsícem

    Thank you Striver. I owe you❤

  • @lakshmiprasanna7058
    @lakshmiprasanna7058 Před rokem +1

    Understood 💯💯💯

  • @rajatpatra2593
    @rajatpatra2593 Před rokem +2

    Understood ❤️

  • @parshchoradia9909
    @parshchoradia9909 Před rokem

    Understood Sir!

  • @konankikeerthi
    @konankikeerthi Před měsícem

    Thanks bro. Understood

  • @YourCodeVerse
    @YourCodeVerse Před 9 měsíci

    Understood✅🔥🔥

  • @rakshanaravindran9809
    @rakshanaravindran9809 Před 10 měsíci

    Thank you!!

  • @user-is6ky7pp2n
    @user-is6ky7pp2n Před 2 měsíci

    Understood !! 😍😍

  • @nopecharon
    @nopecharon Před 11 měsíci +1

    you are topG of DSA

  • @swapnilingale4164
    @swapnilingale4164 Před 10 měsíci

    Nice explation ❤

  • @samyakagarwal1777
    @samyakagarwal1777 Před 3 měsíci

    thank you so much

  • @mozsty
    @mozsty Před 2 měsíci

    very nice. .thankyou

  • @code710
    @code710 Před rokem +6

    Hi bhaiya it would be really helpful if you can give similar question links for practise after every question explanation!!

  • @mehulthuletiya5638
    @mehulthuletiya5638 Před rokem +10

    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

  • @kingbadshah452
    @kingbadshah452 Před 6 měsíci

    understood striver thanks

  • @her_soulmate
    @her_soulmate Před 10 měsíci

    Understood 🎉

  • @UtkarshSingh575
    @UtkarshSingh575 Před 3 měsíci +1

    Understood!

  • @shobhitsrivastava1223
    @shobhitsrivastava1223 Před 11 měsíci

    Understood ❤

  • @sarangkumarsingh7901
    @sarangkumarsingh7901 Před 4 měsíci

    Awesome Awesome Sir...............

  • @YerramArun
    @YerramArun Před rokem

    Understood❤❤

  • @schan263
    @schan263 Před 8 měsíci

    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.

  • @aashapun6533
    @aashapun6533 Před 8 měsíci

    The Best♥

  • @user-sp8ne7hj3n
    @user-sp8ne7hj3n Před 8 měsíci

    nice ..........explanation

  • @chinmay6152
    @chinmay6152 Před rokem

    Understood😁😉

  • @anuragroy9045
    @anuragroy9045 Před 11 měsíci

    understood!!!

  • @user-nk1mb5fy7j
    @user-nk1mb5fy7j Před rokem

    UNDERSTOOD

  • @DTALKS01
    @DTALKS01 Před měsícem

    for me optimal is little hard but after see 2-3 time video , got easly understand

  • @satyam5613
    @satyam5613 Před 3 měsíci

    thank you

  • @Hariharan0606
    @Hariharan0606 Před rokem

    Amazing

  • @user-uv5or5bm2c
    @user-uv5or5bm2c Před 5 měsíci

    Understood.

  • @saicharanthammi143
    @saicharanthammi143 Před 4 měsíci

    Thanku sir

  • @ashj1165
    @ashj1165 Před 6 měsíci

    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 Před 6 měsíci

      if you select no element in sub array then , map[0]=1

  • @gagan_.hegde14
    @gagan_.hegde14 Před 2 měsíci

    underrstood

  • @culeforever5408
    @culeforever5408 Před 9 měsíci +1

    undestood ✌

  • @Unknown-uq1yo
    @Unknown-uq1yo Před 6 dny

    Understood

  • @piyushnandardhane1432

    Please also make video for count pairs with given sum and divisible by k

  • @deepanshuverma6237
    @deepanshuverma6237 Před měsícem

    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

  • @impalash_ag
    @impalash_ag Před 29 dny

    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

  • @biswadevsarkar2830
    @biswadevsarkar2830 Před měsícem

    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++;

  • @rohan8758
    @rohan8758 Před 2 měsíci

    Awesome explanation, one approach of sliding window will not work in this problem if array contains negative elements also.

  • @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??

  • @mriduljain1981
    @mriduljain1981 Před 11 měsíci

    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 Před 10 měsíci

      It will fail .arr[]=[1] k=0

    • @mriduljain1981
      @mriduljain1981 Před 10 měsíci

      @@amitranjan6998 yes we just need to add a condition of left

  • @nishantkumar1276
    @nishantkumar1276 Před rokem

    Sir, May I know time complexity of the optimal approach in java

  • @Hustler0109
    @Hustler0109 Před rokem +5

    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

  • @PranaliAwhale
    @PranaliAwhale Před měsícem +1

    understood

  • @Rishabh3164
    @Rishabh3164 Před 8 měsíci

    Can we do this first calculate the prefix sum and than suffix sum and than we subtract each and sum the prefix and suffix

  • @nikiteshnandale8264
    @nikiteshnandale8264 Před rokem +4

    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  Před rokem +13

      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 Před rokem

      ​@@takeUforwardand we love you for that too,
      It's sort of unconditional 😂

  • @VineetKumar-fk2rl
    @VineetKumar-fk2rl Před 8 měsíci +1

    We can also solve this problem in O(1) space complexity but the T.C will be 2N using two pointer approach.

  • @saileshsirari2014
    @saileshsirari2014 Před 2 měsíci

    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

  • @VnALShorts
    @VnALShorts Před rokem

    22:54 *please explain what lines*
    int remove = presum - k;
    count += mp[remove];
    mp[presum]++;
    do ?

  • @user-ed8bc2hg5o
    @user-ed8bc2hg5o Před 21 hodinou

    Understand

  • @meghnakhaitan2495
    @meghnakhaitan2495 Před rokem +1

    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

  • @nookalareshwanth1785
    @nookalareshwanth1785 Před 6 měsíci

    nice

  • @shaiksoofi3741
    @shaiksoofi3741 Před 5 měsíci

    tq

  • @AbhishekKumar-cd4gg
    @AbhishekKumar-cd4gg Před 9 měsíci

    understood , but took tom much time to understood how to update the frequency if there exist a prefix sum in the HashMap

  • @opgaming-sl8ze
    @opgaming-sl8ze Před rokem

    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;
    }

  • @shubhambhardwaj8982
    @shubhambhardwaj8982 Před rokem

    Hey Strivers Good explanation ❤
    Can you just change the gfg link of this question it redirect to same page.
    Once again thank you 👍

  • @AdityaKumar-ow1rh
    @AdityaKumar-ow1rh Před rokem

    we can also do this problem by sliding window technique

  • @rowgha2710
    @rowgha2710 Před 11 měsíci +1

    What if the array contains 0s?