Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK

Sdílet
Vložit
  • čas přidán 21. 06. 2024
  • iPad PDF Link - github.com/MAZHARMIK/Intervie...
    Whatsapp Community Link : www.whatsapp.com/channel/0029...
    This is the 93rd Video of our Playlist "Array 1D/2D : Popular Interview Problems" by codestorywithMIK
    In this video we will try to solve a very good Array based Problem : Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK
    I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
    We will do live coding after explanation and see if we are able to pass all the test cases.
    Also, please note that my Github solution link below contains both C++ as well as JAVA code.
    Problem Name : Count Number of Nice Subarrays | 2 Approaches | Similar Concept | Leetcode 1248 | codestorywithMIK
    Company Tags : will update soon
    My solutions on Github(C++ & JAVA) : github.com/MAZHARMIK/Intervie...
    Leetcode Link : leetcode.com/problems/count-n...
    My DP Concepts Playlist : • Roadmap for DP | How t...
    My Graph Concepts Playlist : • Graph Concepts & Qns -...
    My Recursion Concepts Playlist : • Introduction | Recursi...
    My GitHub Repo for interview preparation : github.com/MAZHARMIK/Intervie...
    Instagram : / codestorywithmik
    Facebook : / 100090524295846
    Twitter : / cswithmik
    Subscribe to my channel : / @codestorywithmik
    ╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
    ║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
    ╠╗║╚╝║║╠╗║╚╣║║║║║═╣
    ╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
    Summary :
    Approach 1: Using Prefix Sum and Hashmap
    Time Complexity (T.C): O(n)
    Space Complexity (S.C): O(n)
    This approach leverages the prefix sum technique combined with a hashmap to efficiently count subarrays with exactly k odd numbers.
    Initialization:
    mp (unordered_map) to store the frequency of prefix sums.
    Variables: n (length of nums), count (result count), and currSum (current prefix sum).
    Iterate Through Array:
    For each element, update currSum by adding 1 if the element is odd (nums[i] % 2), else add 0.
    Check if currSum - k exists in mp. If it does, increment count by the frequency of currSum - k.
    Update mp to include the current currSum.
    This method ensures that each subarray's prefix sum is calculated in linear time, and the hashmap provides efficient lookups for the required subarray sums.
    Approach 2: Sliding Window (Khandani Template with a Twist)
    Time Complexity (T.C): O(n)
    Space Complexity (S.C): O(1)
    This approach utilizes a sliding window technique to dynamically count subarrays containing exactly k odd numbers.
    Initialization:
    Variables: n (length of nums), oddCount (number of odd numbers in the current window), count (subarrays ending at the current position), result (total count of valid subarrays), and two pointers i and j (window boundaries).
    Sliding Window:
    Iterate with j from 0 to n-1. For each element:
    If the element is odd, increment oddCount and reset count to 0.
    While oddCount equals k, increment count and adjust the window by incrementing i and decreasing oddCount if the element at i is odd.
    Add count to result.
    This method maintains a sliding window that expands and contracts based on the number of odd numbers, ensuring efficient computation in linear time with constant space.
    ✨ Timelines✨
    00:00 - Introduction
    #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook #leetcode #computerscience #leetcodesolutions #leetcodequestionandanswers #code #learning #dsalgo #dsa #newyear2024

Komentáře • 74

  • @codestorywithMIK
    @codestorywithMIK  Před měsícem +17

    If anyone is confused why we have to reset prevCount = 0.
    Let's see this with an example :
    nums = {2, 1}, k = 1
    we have two subarrays having oddCount --> {2, 1}, {1}
    COUNT_NICE_SUBARRAY = 2
    Now, suppose we have one more integer 2 . our array looks like --> {2, 1, 2}, k = 1
    If you see, addition of this extra 2 will not impact the oddCount because this 2 is even.
    So, we again get two more subarrays by including this 2 with previous two nice subarrays {2, 1} and {1}
    so we get {2, 1, 2}, {1, 2}
    So, over all Nice subarrays becomes - {2, 1}, {1}, {2, 1, 2}, {1, 2}
    Now, COUNT_NICE_SUBARRAY = 4
    Now, let's take one more example : Let's say the one more integer after {2, 1} is 1
    So, our array becomes -> {2, 1, 1}
    Let's break it again -> from {2, 1} we had {2, 1}, {1} i.e. COUNT_NICE_SUBARRAY = 2
    Now, when 1 comes, this is another Odd number so oddCount is affacted and hence we can't add previousCount = 2 to our result because {2, 1, 1} doesn't have k = 1 odd numbers. It has 2 odd numbers.
    So, we need to start from fresh and hence prevCount is made 0.
    Now, the new subarray having k = 1 oddCount is the {1}
    so we got one nice subarray now.
    COUNT_NICE_SUBARRAY = 2 + 1 = 3 (correct output)

    • @EB-ot8uu
      @EB-ot8uu Před měsícem

      ek do example dry run karke mai samajh gaya ye. thanks a lot

  • @nawazthezaifre8870
    @nawazthezaifre8870 Před měsícem +15

    Other youtuber max 9 minutes explanation while MIK comes with 32 minutes videos surely it has something extraordinary..

  • @KamnaPlacement
    @KamnaPlacement Před měsícem +16

    Honestly i find your explanation the best in whole yt community ..since i found your channel never looked back , for every topic i just look for your video😊

  • @harshpandey7970
    @harshpandey7970 Před měsícem +6

    sir your channel is the most genuine channel ive seen, i have been able to build consistency on leetcode solving daily potd by the help of our approach and process of solving a question

  • @23cash86
    @23cash86 Před měsícem +3

    25:00 this is why I come to your channel,thanks a lot

  • @SR-my8qv
    @SR-my8qv Před měsícem +6

    finally todays my 10th day of leetcode and i was able to code it after understanding the concept. thank you.

  • @user-kj7eh9ke5n
    @user-kj7eh9ke5n Před měsícem +13

    Can you please try to upload videos a little early if possible.
    Your type of explanation is realy amazing!😃

  • @vikassinghbisht7305
    @vikassinghbisht7305 Před 24 dny +1

    great explanation bhaiya such a good quality content you are posting on youtube for free

  • @vanshrana7807
    @vanshrana7807 Před měsícem +5

    Hi bhai, following you from the last 6-7 months ques bn rhe hai thanks for such simple and great explanations ❤
    Bs ab jaldi se segment tree video no. 4 upload krdo

  • @morty6456
    @morty6456 Před měsícem +5

    You actually taking my suggestion seriously, that's really cool bro.
    Keep up the good work 😎

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

    top class explaination as usual

  • @adityakurhade1531
    @adityakurhade1531 Před měsícem +3

    i_bada approach, those who follow MIK might know this 😃
    I feel this approach is well-suited for these kinds of problems and is quite intuitive.
    public class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
    int i = 0, i_bada = 0;
    int j = 0 ;
    int res = 0;
    int odd_count = 0;
    while(j < nums.length){
    if(nums[j] % 2 == 1)
    odd_count++;
    while(odd_count > k){
    if(nums[i] % 2 == 1)
    odd_count--;
    i++;
    i_bada = i;
    }
    while(i < nums.length && nums[i] % 2 == 0)
    i++;
    if(odd_count == k){
    res += i - i_bada + 1;
    }
    j++;
    }
    return res;
    }
    }

  • @vineetkumarmotwani474
    @vineetkumarmotwani474 Před měsícem +11

    0:00 Problem Introduction
    2:04 Approach-1 (Using map)
    18:09 Approach-1 code
    20:17 Approach-2 (Sliding Window)
    30:27 Approach-2 code

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

    Bhaiya kisi video mein apne daily routine mein baarien mein batana how u are managing ur work , utube and personal life

  • @B-Billy
    @B-Billy Před měsícem +1

    Your Hand Writing is really awesome!! Thanks for awesome explanation!

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

    ekdm same leetcode 560 jaisa hai ye. dobara samjhane k lie thank you bhai. this shows your dedication towards providing quality content. thanks a lot

  • @EB-ot8uu
    @EB-ot8uu Před měsícem

    First approach was very clever. sliding window detect karliya tha maine but beech me stuck hogaya tha, then exactly wahi cheez aapne batai. thanks a lot

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

    Sir can u please start uploading leetcode weekly and biweekly contest solution videos. That would be a great help!!

  • @NITian-Priyanshu
    @NITian-Priyanshu Před měsícem +1

    example sir aap aisa choose krte ho ki kai test case clear ho jaye

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

    You are the best MIK

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

    Good explanation 👏 👍

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

    Nice video

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

    Itna mast kaise parha lete ho yaar 🙏🏻

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

    codechef ka contest discussion bhi start kariye sir please

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

    thank you :-)

  • @gui-codes
    @gui-codes Před měsícem +3

    For those who are wondering why we need to reset the prevCount to 0 when we see a new Odd number (nums[j]).
    Just try this leetcode's first Example : [1,1,2,1,1], k = 3 and you will see you are overcounting. simple dry run will help.

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

    nice...

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

    butter. what a fine explanation. Your choice of examples are really good. how do you come up with those. for example in the second approach example : {2, 1}, k = 1 was apt and helped me clear all my doubts

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

    For hashmap approach
    if arr = [2, 4, 6] ans k = 1
    wont the result be 3
    because oddCont - k => 0 - 1 = -1
    this will come 3 times?

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

    ❤❤

  • @gauravbanerjee2898
    @gauravbanerjee2898 Před měsícem +2

    Thanks a lot bhaiya
    Congrats for 53k subs 🥳🥳
    Lekin 2nd approach ache se samajh nahi aya 🙂

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

      Thank you Gaurav ❤️
      I would love to know where exactly in approach-2 you felt stuck. I will be more than happy to clear it here ❤️🙏

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

      @@codestorywithMIK Bhaiya prevCount variable ka use case and usko reset karne ka reason samajh nahi aya thik se

    • @codestorywithMIK
      @codestorywithMIK  Před měsícem +4

      @@gauravbanerjee2898 Sure, let me try to explain with a small example. I have Pinned my comment above for this.
      If anyone is confused why we have to reset prevCount = 0.
      Let's see this with an example :
      nums = {2, 1}, k = 1
      we have two subarrays having oddCount --> {2, 1}, {1}
      COUNT_NICE_SUBARRAY = 2
      Now, suppose we have one more integer 2 . our array looks like --> {2, 1, 2}, k = 1
      If you see, addition of this extra 2 will not impact the oddCount because this 2 is even.
      So, we again get two more subarrays by including this 2 with previous two nice subarrays {2, 1} and {1}
      so we get {2, 1, 2}, {1, 2}
      So, over all Nice subarrays becomes - {2, 1}, {1}, {2, 1, 2}, {1, 2}
      Now, COUNT_NICE_SUBARRAY = 4
      Now, let's take one more example : Let's say the one more integer after {2, 1} is 1
      So, our array becomes -> {2, 1, 1}
      Let's break it again -> from {2, 1} we had {2, 1}, {1} i.e. COUNT_NICE_SUBARRAY = 2
      Now, when 1 comes, this is another Odd number so oddCount is affacted and hence we can't add previousCount = 2 to our result because {2, 1, 1} doesn't have k = 1 odd numbers. It has 2 odd numbers.
      So, we need to start from fresh and hence prevCount is made 0.
      Now, the new subarray having k = 1 oddCount is the {1}
      so we got one nice subarray now.
      COUNT_NICE_SUBARRAY = 2 + 1 = 3 (correct output)

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

      @@codestorywithMIK Thanks a lot bhaiya Bahut ache se explain kardiya apne ❤❤. really sorry for bothering you, but the way you respond to each query in the comment section is what separates you from other creators. Thank you so much❤❤

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

      @gauravbanerjee2898
      Means a lot ❤️🙏

  • @mohitbi1
    @mohitbi1 Před 8 dny

    Sliding window approach not working for -
    int[] nums = { 1, 1, 1, 1, 1 };
    int k = 1;

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

    app ka solution kis time pai aata hai mostly

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

    sir please make solution of 3181. Maximum Total Reward Using Operations II using bitset; having trouble understanding it; and thanks for the segment tree playlist

  • @ManojKrVerma-vw4dx
    @ManojKrVerma-vw4dx Před měsícem

    sliding window problem mei aap ko kaise idea laga ki ye example kaam krega ki nahi...
    qki mere se jaise hi ek test case paas hota to code kr deta phir fail ho jata hai...
    Please help for the approach... what should be the minimum no of test cases we should try on before writing the code.... @codestorywithmik

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

    bhai second wali approach samjh hi nhi ayi kiya kya, i wrote the queue code by self, but space na use karne wali approach nhi samjh ayi

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

      Hi Sahil,glad to know you solved queue approach on your own.
      Would you share where exactly you got stuck in the 2nd approach. I will try to explain here.
      Also please see my pinned comment above ❤️

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

    can we not use take and not take approach to find all subarray with that specific sum of odd number MIK?

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

      For subarray, you need to have consecutive elements. If you don’t take an element you will have to start a new subarray. Or i think it will be a little tricky to handle a lot of corner cases

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

    Is segment Tree frequenty asked topic in Interview? As my internship session started in July in my college.
    Should I study this topic or focus on the preparation for Intership...

    • @the_star_harsh
      @the_star_harsh Před měsícem +2

      For internships no company as suck ask segment trees and some high paying companies ask segment trees in placement. So focus more on Topics such as Arrays, LinkedList, Stack, Queue, Graph, Tree and maps for internship.

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

      @@the_star_harsh Thanks bro❤❤

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

    Bhaiya segment tree ka next video kab aarha hai

  • @adityaraj-zm7zk
    @adityaraj-zm7zk Před měsícem

    bhaiya please provide this side pdf and all next problem please provides slides for better understanding and attached the pdf also for this question and one thing bhaiya apke samjane ka tarika alag hai jisme maja ata hai

  •  Před měsícem

    i get idea of approach 3rd-- but stuck and got wrong-- here is my code
    class Solution {
    public:
    int countSubarraysWithKOddNumbers(int i, int oddCount, const vector& nums, int n, int k) {
    if (i == n) {
    return oddCount == k ? 1 : 0;
    }
    int includeCurrent = countSubarraysWithKOddNumbers(i + 1, oddCount + (nums[i] % 2 == 1), nums, n, k);
    int excludeCurrent = countSubarraysWithKOddNumbers(i + 1, oddCount, nums, n, k);
    return includeCurrent + excludeCurrent;
    }
    int numberOfSubarrays(vector& nums, int k) {
    int n = nums.size();
    return countSubarraysWithKOddNumbers(0, 0, nums, n, k);
    }
    };
    i want to do it simply but use of recursion , no dp , just to run code , not to submit because it has exponential 2 time complexity. if anyone correct my code , i am really become so grateful.
    hope for fast reply , if you can roast my code , it is also good for me .

  • @xiaoshen194
    @xiaoshen194 Před měsícem +4

    Did it easily. I just wanted to inquire like how many videos can we expect in Segment Tree playlist? So that i can plan accordingly to do cses

    • @codestorywithMIK
      @codestorywithMIK  Před měsícem +9

      For covering concepts, there will be only 2-3 more videos. Rest will be answered only. I’ll try to upload one tomorrow as I am out today ❤❤❤

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

      ​@@codestorywithMIKtry to cover Fenwick tree also

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

      Noted Sahil ❤️

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

      @@codestorywithMIK there is lot to learn from ur videos in terms of approaching to solution of any problem
      ... Sir placement season is not too far so try to make dp and graph k hard question from leetcode... It'll be very helpful

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

    sliding window ka ye twist thora confusing tha......

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

    bhaeeya prevcount ko reset kiw kr rhey hai smjh nhi aaaya

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

    BHAI MAI BHI QUESTION KARTA HO BUT BNTA NHI HAI KYA KARU

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

      us bhai us, 50 din se daily 1 ques kar rha hu, about 15 bhi khud nhi kar paya.

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

    bhaiya are you not even reading my comment or ignoring me . I keep requesting from your previous last videos for solution of leetcode 2659 , make array empty but why are you even not clarifying whether you will make or not , or do you also not able to understand the intuition of this problem?If thats so , its fine i wasnt able to understand the intuition thats why i was requesting you. Not the segment tree approach but the other one.

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

      Hi there,
      Actually i get really occupied due to multiple other activities and get less time. I will try to cover this soon.
      Thanks ❤️❤️❤️

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

      @@codestorywithMIK thank you so much bhaiya you are my only hope, i really got distressed there that's why i wrote like that very sorry 🥺.

    • @gui-codes
      @gui-codes Před měsícem +1

      are bhai itna gussa. araam se bhai. working professional hain wo, time nikalna mushkil to hota hi hoga.

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

      @@gui-codes hn bhai

  •  Před měsícem

    i get idea of approach 3rd-- but stuck and got wrong , i want to do it simply but use of recursion , no dp , just to run code , not to submit because it has exponential 2 time complexity. if anyone correct my code , i am really become so grateful. here is my code
    class Solution {
    public:
    int countSubarraysWithKOddNumbers(int i, int oddCount, const vector& nums, int n, int k) {
    if (i == n) {
    return oddCount == k ? 1 : 0;
    }
    int includeCurrent = countSubarraysWithKOddNumbers(i + 1, oddCount + (nums[i] % 2 == 1), nums, n, k);
    int excludeCurrent = countSubarraysWithKOddNumbers(i + 1, oddCount, nums, n, k);
    return includeCurrent + excludeCurrent;
    }
    int numberOfSubarrays(vector& nums, int k) {
    int n = nums.size();
    return countSubarraysWithKOddNumbers(0, 0, nums, n, k);
    }
    };
    hope for fast reply , if you can roast my code , it is also good for me .

  • @mohitbi1
    @mohitbi1 Před 8 dny

    sliding window approach not working for int[] nums = { 1, 1, 1, 1, 1 }; int k = 1;